package com.dhcc.DRGsHosp.facade.impl;

import com.dhcc.DRGsHosp.application.*;
import com.dhcc.DRGsHosp.core.domain.*;
import com.dhcc.DRGsHosp.facade.DrgsIndexCalFacade;
import com.dhcc.DRGsHosp.facade.DrgsService;
import com.dhcc.DRGsHosp.facade.dto.DepDataDto;
import com.dhcc.DRGsHosp.facade.dto.DepDetail;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import com.dhcc.DRGsHosp.facade.dto.MonitorDep;
import com.dhcc.DRGsHosp.facade.impl.assembler.IndexCalAssembler;
import com.dhcc.DRGsHosp.infra.util.ConstantEnum;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.QueryChannelService;
import org.dom4j.*;
import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.koalacommons.resourceloader.util.StringUtils;
import org.openkoala.security.core.domain.User;
import org.openkoala.security.facade.SecurityConfigFacade;
import org.openkoala.security.facade.command.ChangeUserEmailCommand;
import org.openkoala.security.facade.command.ChangeUserPasswordCommand;
import org.openkoala.security.facade.command.ChangeUserTelePhoneCommand;
import org.openkoala.security.facade.command.CreateUserCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.xml.sax.InputSource;

import javax.jws.WebService;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



/**
 * @title		:DRGsServiceImpl.java
 * @description	:
 * @author		:fuchengzhi
 * @date		:2014年10月17日下午2:33:10
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
@WebService(endpointInterface="com.dhcc.DRGsHosp.facade.DrgsService", serviceName="DrgsService",targetNamespace="DrgsService")
public class DrgsServiceImpl implements DrgsService {
	
	private static final Logger logger = LoggerFactory.getLogger(DrgsServiceImpl.class);

	private QueryChannelService queryChannel;
	
	private EntityRepository repository;
	
	@Autowired
	private XmlStructureApplication xmlStructureApplication;
	
	@Autowired
	private MedicalRecordApplication medicalRecordApplication;
	
	@Autowired
	private DepartmentApplication departmentApplication;
	
	@Autowired
	private MedinsApplication medinsApplication;
	
	@Autowired
    private SecurityConfigFacade securityConfigFacade;
	
	@Autowired 
	private SystemConfigApplication systemConfigApplication;
	
	@Autowired
	private DrgsIndexCalFacade drgsIndexCalFacade;
	
	@Autowired
	private DrgsServiceApplication drgsServiceApplication;
	
	@Autowired
    private DrgsIndexCalApplication  drgsIndexCalApplication;
	
	@Autowired
	private DRGVersionApplication drgVersionApplication;
	
	@Autowired
	private DRGsApplication drgsApplication;
	
	@Autowired
	private PatientDrgApplication patientDrgApplication ;
	
	@Autowired
	private AnnualSTDApplication annualSTDApplication;
	
	private EntityRepository getRepository() {
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository");
		}
		return repository;
	}
	
    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
    
    @Override
	public String hospitalCMI(String paramStr) {
    	List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateType = null;
		String date = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateType = strings[0].toString();
			date = strings[1].toString();
		}
		DepDataDto dto = new DepDataDto();
		dto.setDate(date);
		dto.setDateType(dateType);
		getHospData(dto, "CMIDRGCount");
		
		List<MonitorDep> monitorDeps = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorDeps){
			String hospCMI = "";
			String hospDrgCount = "";
			List<DepDetail> depDetails = mDep.getDepDetails();
			
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				if ("CMI".equals(dDetail.getQuotaCode())) {
					hospCMI = quotaValue;
				} else if ("DRGCount".equals(quotaCode)) {
					hospDrgCount = quotaValue;
				}
			}	
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("date", date);
			data.put("DrgCnt", hospDrgCount);
			data.put("CMI", hospCMI);
			dataList.add(data);
		}
		if (monitorDeps==null || monitorDeps.size()==0) {
			errMSG = date+"没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	@Override
	public String depCMI(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		DepDataDto dto = new DepDataDto();
		String date = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] params = paramStr.split("\\^");
			if (params.length==2) {
				date = params[1];
				dto.setDateType(params[0]);
				dto.setDate(params[1]);
			} else if (params.length == 3) {
				date = params[1]+"~"+params[2];
				dto.setDepCode(params[0]);
				dto.setDateFrom(params[1]);
				dto.setDateTo(params[2]);
			}
		} else {
			return "{status:\"-1\",errMSG:\"传入参数错误\"}";
		}
		
		getDepData(dto, "CMIDRGCount");
		
		List<MonitorDep> monitorDeps = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorDeps){
			String depCMI = "";
			String depDrgCount = "";
			String depCode = mDep.getDepCode();
			String depName = mDep.getDepName();
			List<DepDetail> depDetails = mDep.getDepDetails();
			
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				if ("CMI".equals(dDetail.getQuotaCode())) {
					depCMI = quotaValue;
				} else if ("DRGCount".equals(quotaCode)) {
					depDrgCount = quotaValue;
				}
			}	
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("DepCode", depCode);
			data.put("DepName", depName);
			data.put("DepCMI", depCMI==null?0:depCMI);
			data.put("DepDRGCount", depDrgCount);
			dataList.add(data);
		}
		if (monitorDeps==null || monitorDeps.size()==0) {
			errMSG = date+"没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	@Override
	public String depDRGsCMI(String dateFrom, String dateTo, String depCodes) {
		
		//所有科室
		List<Department> depList = departmentApplication.findAllDepartment();
		
		Map<String, String> hisDepCodeMap = new HashMap<String, String>();//科室名称代码信息
		for (Department dep : depList) {
			if (dep.getDepHis()!=null) {
				String[] depHis = dep.getDepHis().split(",");
				for (String hisName : depHis) {
					hisDepCodeMap.put(hisName, dep.getDepCode());
				}
			}
			if (dep.getDepHisCode()!=null) {
				String[] depHisCode = dep.getDepHisCode().split(",");
				for (String hisCode : depHisCode) {
					hisDepCodeMap.put(hisCode, dep.getDepCode());
				}
			}
		}
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		DepDataDto dto = new DepDataDto();
		String date = null;
		
		if (StringUtils.hasLength(dateFrom) && StringUtils.hasLength(dateTo) && StringUtils.hasLength(depCodes)) {
			date = dateFrom+"~"+dateTo;
			String[] hisDeps = depCodes.split("\\^");
			List<String> deps = new ArrayList<String>();
			for (String dep : hisDeps) {
				if (hisDepCodeMap.get(dep)!=null) {
					deps.add(hisDepCodeMap.get(dep));
				} else {
					deps.add(dep);
				}
			}
			dto.setDepCode(org.apache.commons.lang.StringUtils.join(deps, ","));
			dto.setDateFrom(dateFrom);
			dto.setDateTo(dateTo);
		} else {
			return "{status:\"-1\",errMSG:\"传入参数错误\"}";
		}
		
		getDepData(dto, "CMIDRGCount");
		
		List<MonitorDep> monitorDeps = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorDeps){
			String depCMI = "";
			String depDrgCount = "";
			String depCode = mDep.getDepCode();
			String depName = mDep.getDepName();
			List<DepDetail> depDetails = mDep.getDepDetails();
			
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				if ("CMI".equals(dDetail.getQuotaCode())) {
					depCMI = quotaValue;
				} else if ("DRGCount".equals(quotaCode)) {
					depDrgCount = quotaValue;
				}
			}	
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("DepCode", depCode);
			data.put("DepName", depName);
			data.put("DepCMI", depCMI==null?0:depCMI);
			data.put("DepDRGCount", depDrgCount);
			dataList.add(data);
		}
		if (monitorDeps==null || monitorDeps.size()==0) {
			errMSG = date+"没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.ws.service.DRGsService#depEfficiency(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public String depEfficiency(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateType = null;
		String date = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateType = strings[0].toString();
			date = strings[1].toString();
		}
		DepDataDto dto = new DepDataDto();
		dto.setDate(date);
		dto.setDateType(dateType);
		getDepData(dto, "TimeFeeEff");
		
		List<MonitorDep> monitorDeps = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorDeps){
			String costEfficiency = "";
			String daysEfficiency = "";
			String depCode = mDep.getDepCode();
			String depName = mDep.getDepName();
			List<DepDetail> depDetails = mDep.getDepDetails();
			
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				if ("FeeEff".equals(dDetail.getQuotaCode())) {
					costEfficiency = quotaValue;
				} else if ("TimeEff".equals(quotaCode)) {
					daysEfficiency = quotaValue;
				}
			}	
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("DepCode", depCode);
			data.put("DepName", depName);
			data.put("DepCostEfficiency", costEfficiency);
			data.put("DepDaysEfficiency", daysEfficiency);
			dataList.add(data);
		}
		if (monitorDeps==null || monitorDeps.size()==0) {
			//ret = "<Status>"+date+"没有查询到数据</Status>";
			errMSG = date+"没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	@Override
	public String depInfAndLRM(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateType = null;
		String date = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateType = strings[0].toString();
			date = strings[1].toString();
		}
		DepDataDto dto = new DepDataDto();
		dto.setDate(date);
		dto.setDateType(dateType);
		getDepData(dto, "Risk1Risk2Ratio");
		
		List<MonitorDep> monitorDeps = dto.getMonitorDeps();

		for (MonitorDep mDep:monitorDeps) {
			String depCode = mDep.getDepCode();
			String depName = mDep.getDepName();
			String risk1Ratio = "";
			String risk2Ratio = "";

			List<DepDetail> depDetails = mDep.getDepDetails();
			
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				if ("Risk1Ratio".equals(dDetail.getQuotaCode())) {
					risk1Ratio = quotaValue;
				} else if ("Risk2Ratio".equals(quotaCode)) {
					risk2Ratio = quotaValue;
				}
			}
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("DepCode", depCode);
			data.put("DepName", depName);
			data.put("Risk1Ratio", risk1Ratio);
			data.put("Risk2Ratio", risk2Ratio);
			data.put("Unit", "%");
			dataList.add(data);
		}
		if (monitorDeps==null || monitorDeps.size()==0) {
			errMSG = date+"没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	/**
	 * 
	 * @methodname    :getHospCMI
	 * @description   :取得指定时间全院的各DRG组及其权重和人数 
	 * @param         :@param dateType
	 * @param         :@param date
	 * @param         :@return
	 * @author        :fuchengzhi
	 * @return        :List<DrgsInfoDto>
	 * @date          :2014年10月17日下午4:49:17
	 */
	/*
	private List<DrgsInfoDto> getHospCMI(String dateType, String date){
		StringBuffer sql = new StringBuffer();
		sql.append("select ld.pardrg_code as drg_code, drg.drg_weight, "
				+ " count(ld.pardrg_code) as drg_pat_count "
				+ " from drgs.t_logicdata ld "
				+ " left join drgs.t_drgs drg on ld.pardrg_code=drg.drg_code ");
		
		//月
		if (dateType.equals("1")){		
			sql.append(" where to_char(ld.out_date, 'yyyy-mm') = '"+date+"' ");	
		//年	
		} else if(dateType.equals("2")){
			sql.append(" where to_char(ld.out_date, 'yyyy') = '"+date+"' ");
		} else {
			sql = null;
		}
		sql.append(" group by ld.pardrg_code,drg.drg_weight");
		//List<DrgsInfoDto> list = jdbcTemplateObjWrapper.queryAllMatchList(sql.toString(), DrgsInfoDto.class, null);
		List<Object[]> objectlist = getQueryChannelService().createSqlQuery(sql.toString()).list();
		List<DrgsInfoDto> list = new ArrayList<DrgsInfoDto>();
		for (Object[] objects : objectlist) {
			DrgsInfoDto drgsInfoDto = new DrgsInfoDto();
			drgsInfoDto.setDrgCode(objects[0]+"");
			drgsInfoDto.setDrgWeight(Double.valueOf(objects[1]+""));
			drgsInfoDto.setDrgPatCount(Integer.valueOf(objects[2]+""));
			list.add(drgsInfoDto);
		}
		return list;
		
	}
	*/
	/**
	 * 
	 * @methodname    :getDepDrgInfo
	 * @description   :获取指定时间内各科室下的各DRG组信息 
	 * @param         :@param dateType
	 * @param         :@param date
	 * @param         :@return
	 * @author        :fuchengzhi
	 * @return        :List
	 * @date          :2014年10月17日下午6:02:57
	 */
	/*
	private List<DepDrgDto> getDepDrgInfo(String dateType, String date){
		
		String sqlDep = "select dep.dep_code,dep.dep_name "
				+ " from drgs.t_department dep where dep.dep_type='E'";
		//List<DepDrgDto> listDep = jdbcTemplateObjWrapper.queryAllMatchList(sqlDep, DepDrgDto.class, null);
		List<DepDrgDto> listDep = new ArrayList<DepDrgDto>();
		List<Object[]> objectList = getQueryChannelService().createSqlQuery(sqlDep).list();
		for (Object[] objects : objectList) {
			DepDrgDto depDrgDto = new DepDrgDto();
			depDrgDto.setDepCode(objects[0]+"");
			depDrgDto.setDepName(objects[1]+"");
			listDep.add(depDrgDto);
		}
		
		
		if (dateType.equals("1")){		
			for (DepDrgDto list:listDep) {
				String depCode = list.getDepCode();
				String sqlDepDrg = "select ld.pardrg_code as drg_code, drg.drg_weight, "
						+ " count(ld.pardrg_code) as drg_pat_count "
						+ " from drgs.t_logicdata ld "
						+ " left join drgs.t_drgs drg on ld.pardrg_code=drg.drg_code "
						+ " where to_char(ld.out_date, 'yyyy-mm') = '"+date+"' "
						+ " and ld.pardep_code='"+depCode+"' "
						+ " group by ld.pardrg_code, drg.drg_weight";
				//List<DrgWeightDto> listDrgWeight = jdbcTemplateObjWrapper.queryAllMatchList(sqlDepDrg, DrgWeightDto.class, null);
				List<DrgWeightDto> listDrgWeight = new ArrayList<DrgWeightDto>();
				List<Object[]> tempList = getQueryChannelService().createSqlQuery(sqlDepDrg).list();
				for (Object[] objects : tempList) {
					DrgWeightDto drgWeightDto = new DrgWeightDto();
					drgWeightDto.setDrgCode(objects[0]+"");
					drgWeightDto.setDrgWeight(Double.valueOf(objects[1]+""));
					drgWeightDto.setDrgPatCount(Integer.valueOf(objects[2]+""));
					listDrgWeight.add(drgWeightDto);
				}
				list.setDrgWeightList(listDrgWeight);
			}
		} else if(dateType.equals("2")){
			for (DepDrgDto list:listDep) {
				String depCode = list.getDepCode();
				String sqlDepDrg = "select ld.pardrg_code as drg_code, drg.drg_weight, "
						+ " count(ld.pardrg_code) as drg_pat_count "
						+ " from drgs.t_logicdata ld "
						+ " left join drgs.t_drgs drg on ld.pardrg_code=drg.drg_code "
						+ " where to_char(ld.out_date, 'yyyy') = '"+date+"' "
						+ " and ld.pardep_code='"+depCode+"' "
						+ " group by ld.pardrg_code, drg.drg_weight";
				//List<DrgWeightDto> listDrgWeight = jdbcTemplateObjWrapper.queryAllMatchList(sqlDepDrg, DrgWeightDto.class, null);
				List<DrgWeightDto> listDrgWeight = new ArrayList<DrgWeightDto>();
				List<Object[]> tempList = getQueryChannelService().createSqlQuery(sqlDepDrg).list();
				for (Object[] objects : tempList) {
					DrgWeightDto drgWeightDto = new DrgWeightDto();
					drgWeightDto.setDrgCode(objects[0]+"");
					drgWeightDto.setDrgWeight(Double.valueOf(objects[1]+""));
					drgWeightDto.setDrgPatCount(Integer.valueOf(objects[2]+""));
					listDrgWeight.add(drgWeightDto);
				}
				list.setDrgWeightList(listDrgWeight);
			}
		} else {
		}
		return listDep;	
	}
	*/
	/**
	 * @methodname    :getDepCostAndDays
	 * @description   :取得指定时间内各科室的费用和住院日信息，及全市同类科室的费用和住院日信息 
	 * @param         :@param dateType
	 * @param         :@param dateFrom
	 * @param         :@param dateTo
	 * @param         :@return
	 * @author        :fuchengzhi
	 * @return        :List
	 * @date          :2014年10月17日下午6:04:53
	 */
	/*
	private List<DepCostDaysDto> getDepCostAndDays(String dateType, String dateFrom,
			String dateTo) {
		String sql = "";
		if (dateType.equals("1")) {
			sql = "select ld.pardep_code as dep_code, dep.dep_name,"
					+ " sum(ld.total_cost)/count(*) as dep_avg_cost, "
					+ " sum(ld.beddays)/count(*) as dep_avg_days "
					+ " from drgs.t_logicdata ld "
					+ " left join drgs.t_department dep on ld.pardep_code = dep.dep_code "
					+ " where to_char(ld.out_date, 'yyyy-mm') between '"+dateFrom+"' and '"+dateTo+"' "
					+ " group by ld.pardep_code,dep.dep_name";
		} else if (dateType.equals("2")) {
			sql = "select ld.pardep_code as dep_code, dep.dep_name,"
					+ " sum(ld.total_cost)/count(*) as dep_avg_cost, "
					+ " sum(ld.beddays)/count(*) as dep_avg_days "
					+ " from drgs.t_logicdata ld "
					+ " left join drgs.t_department dep on ld.pardep_code = dep.dep_code "
					+ " where to_char(ld.out_date, 'yyyy') between '"+dateFrom+"' and '"+dateTo+"' "
					+ " group by ld.pardep_code,dep.dep_name";
		} else {
			
		}
		//List<DepCostDaysDto> list = jdbcTemplateObjWrapper.queryAllMatchList(sql, DepCostDaysDto.class, null);
		List<DepCostDaysDto> list = new ArrayList<DepCostDaysDto>();
		List<Object[]> tempList = getQueryChannelService().createSqlQuery(sql).list();
		for (Object[] objects : tempList) {
			DepCostDaysDto depCostDaysDto = new DepCostDaysDto();
			depCostDaysDto.setDepCode(objects[0]+"");
			depCostDaysDto.setDepName(objects[1]+"");
			depCostDaysDto.setDepAvgCost(Double.valueOf(objects[2]+""));
			depCostDaysDto.setDepAvgDays(Double.valueOf(objects[3]+""));
			list.add(depCostDaysDto);
		}
		return list;
	}
	*/
	/**
	 * @methodname    :getDepInfLRM
	 * @description   : 
	 * @param         :@param dateType
	 * @param         :@param dateFrom
	 * @param         :@param dateTo
	 * @param         :@return
	 * @author        :fuchengzhi
	 * @return        :List<DepInfLRMDto>
	 * @date          :2014年10月17日下午6:50:57
	 */
	/*
	private List<DepInfLRMDto> getDepInfLRM(String dateType, String dateFrom,
			String dateTo) {
		String sql = "";
		if (dateType.equals("1")){
			sql = "select ld.pardep_code as dep_code, dep.dep_name, "
					+ " sum(ld.is_infection) / count(ld.parid) as inf_rate, "
					+ " sum(case when ld.out_way = 5 and drg.drg_lrm = 1 then 1 else 0 end) / count(ld.parid) as lrm_rate "
					+ " from drgs.t_logicdata ld "
					+ " left join drgs.t_department dep on ld.pardep_code = dep.dep_code "
					+ " left join drgs.t_drgs drg on ld.pardrg_code = drg.drg_code "
					+ " where to_char(ld.out_date, 'yyyy-mm') between '"+dateFrom+"' and '"+dateTo+"' "
					+ " group by ld.pardep_code, dep.dep_name";
		} else if (dateType.equals("2")) {
			sql = "select ld.pardep_code as dep_code, dep.dep_name, "
					+ " sum(ld.is_infection) / count(ld.parid) as inf_rate, "
					+ " sum(case when ld.out_way = 5 and drg.drg_lrm = 1 then 1 else 0 end) / count(ld.parid) as lrm_rate "
					+ " from drgs.t_logicdata ld "
					+ " left join drgs.t_department dep on ld.pardep_code = dep.dep_code "
					+ " left join drgs.t_drgs drg on ld.pardrg_code = drg.drg_code "
					+ " where to_char(ld.out_date, 'yyyy') between '"+dateFrom+"' and '"+dateTo+"' "
					+ " group by ld.pardep_code, dep.dep_name";
		}
		//List<DepInfLRMDto> list = jdbcTemplateObjWrapper.queryAllMatchList(sql, DepInfLRMDto.class, null);
		List<DepInfLRMDto> list = new ArrayList<DepInfLRMDto>();
		List<Object[]> tempList = getQueryChannelService().createSqlQuery(sql).list();
		for (Object[] objects : tempList) {
			DepInfLRMDto depInfLRMDto = new DepInfLRMDto();
			depInfLRMDto.setDepCode(objects[0]+"");
			depInfLRMDto.setDepName(objects[1]+"");
			depInfLRMDto.setInfRate(Double.valueOf(objects[2]+""));
			depInfLRMDto.setLrmRate(Double.valueOf(objects[3]+""));
			list.add(depInfLRMDto);
		}
		return list;
	}
	*/
	/**
	 * 
	 * @methodname    :getDepData
	 * @description   :获取所有科室DRG数据 
	 * @param         :
	 * @author        :fuchengzhi
	 * @return        :
	 * @date          :2015年1月14日
	 */
	private void getDepData(DepDataDto dto, String quotaCode) {
		
		String dateType = dto.getDateType();
		String date = dto.getDate();
		String depCode = dto.getDepCode();
		String dateFrom = dto.getDateFrom();
		String dateTo = dto.getDateTo();
		String monitorType = dto.getMonitorType() ;

		IndexCalDTO IndexCalDTO = new IndexCalDTO();
		IndexCalDTO.setQuotaCode(quotaCode);
		IndexCalDTO.setpType("0");
		IndexCalDTO.setDateFrom(dateFrom);
		IndexCalDTO.setDateTo(dateTo);
		if(StringUtils.hasLength(monitorType)){
			IndexCalDTO.setMonitorType(monitorType);
		}else{
			IndexCalDTO.setMonitorType("dep");
		}
		if (depCode != null) {
			//查询指定科室月区间数据
			if ("1400000".equals(depCode)) {//妇科和产科
				//所有科室
				List<Department> depList = departmentApplication.findAllDepartment();
				Map<String, String> depMap = new HashMap<String, String>();//科室名称代码信息
				for (Department dep : depList) {
					depMap.put(dep.getDepName(), dep.getDepCode());
				}
				IndexCalDTO.setDeps(depMap.get("妇科")+","+depMap.get("产科"));
			} else {
				IndexCalDTO.setDeps(depCode);
			}
			IndexCalDTO.setMrType("custom");
			IndexCalDTO.setDateFrom(dateFrom);
			IndexCalDTO.setDateTo(dateTo);
		} else {
			//查询所有科室某月份数据
			if ("1".equals(dateType)) {
				IndexCalDTO.setMrType("M");
				IndexCalDTO.setDateFrom(date);
				IndexCalDTO.setDateTo(date);
			} else if ("2".equals(dateType)) {
				//date = MonitorResultUtil.addMonth(date, GlobalData.CONFIG_MONITOR_YEAR);
				String year = date.substring(0, 4);
				//int month = Integer.valueOf(date.substring(5, 7)+"");
				IndexCalDTO.setMrType("M");
				IndexCalDTO.setDateFrom(year+"-01");
				IndexCalDTO.setDateTo(date);
//				IndexCalDTO.setMrLot(year+"Y"+month+"MC");
			}
		}
		
//		List<Map<String, Object>> dataList = monitorFacade.monitor(IndexCalDTO);
		List<Map<String, Object>> dataList = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(IndexCalDTO);
		
		List<MonitorDep> list = new ArrayList<MonitorDep>();
		for (Map<String, Object> map : dataList) {
			MonitorDep monitorDep = new MonitorDep();
			List<DepDetail> depDetails = new ArrayList<DepDetail>();
			monitorDep.setDepCode(map.get("ccode")+"");
			monitorDep.setDepName(map.get("ddesc")+"");
			for (String key : map.keySet()) {
				DepDetail depDetail = new DepDetail();
				depDetail.setQuotaCode(key);
				depDetail.setQuotaValue(map.get(key)+"");
				depDetails.add(depDetail);
			}
			monitorDep.setDepDetails(depDetails);
			list.add(monitorDep);
		}
		dto.setMonitorDeps(list);
	}
	
	/**
	 * @methodname    :getHospData
	 * @description   :获取全院数据 
	 * @param         :
	 * @author        :fuchengzhi
	 * @return        :
	 * @date          :2015年1月14日
	 */
	private void getHospData(DepDataDto dto, String quotaCode) {
		
		String dateType = dto.getDateType();
		String date = dto.getDate();
		IndexCalDTO IndexCalDTO = new IndexCalDTO();
		IndexCalDTO.setMonitorType("hosp");
		IndexCalDTO.setMrType("year");
		IndexCalDTO.setQuotaCode(quotaCode);
		IndexCalDTO.setpType("0");
		IndexCalDTO.setDateFrom(dto.getDateFrom());
		IndexCalDTO.setDateTo(dto.getDateTo());
		if ("1".equals(dateType)) {
			IndexCalDTO.setMrType("M");
			IndexCalDTO.setDateFrom(date);
			IndexCalDTO.setDateTo(date);
		} else if ("2".equals(dateType)) {
			//date = MonitorResultUtil.addMonth(date, GlobalData.CONFIG_MONITOR_YEAR);
			String year = date.substring(0, 4);
			//int month = Integer.valueOf(date.substring(5, 7)+"");
			IndexCalDTO.setMrType("M");
			IndexCalDTO.setDateFrom(year+"-01");
			IndexCalDTO.setDateTo(date);
			// 注释报错
//			IndexCalDTO.setMrLot(year+"Y"+month+"MC");
		}
		
//		List<Map<String, Object>> dataList = monitorFacade.monitor(IndexCalDTO);
		List<Map<String, Object>> dataList = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(IndexCalDTO);
		List<MonitorDep> list = new ArrayList<MonitorDep>();
		for (Map<String, Object> map : dataList) {
			MonitorDep monitorDep = new MonitorDep();
			List<DepDetail> depDetails = new ArrayList<DepDetail>();
			monitorDep.setDepCode(map.get("ccode")+"");
			monitorDep.setDepName(map.get("ddesc")+"");
			for (String key : map.keySet()) {
				DepDetail depDetail = new DepDetail();
				depDetail.setQuotaCode(key);
				depDetail.setQuotaValue(map.get(key)+"");
				depDetails.add(depDetail);
			}
			monitorDep.setDepDetails(depDetails);
			list.add(monitorDep);
		}
		dto.setMonitorDeps(list);		
	}
	
	
	/**
	 * @methodname    :getDrgsData
	 * @description   :获取DRGs数据
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2017年5月4日
	 */
	private void getDrgsData(DepDataDto dto, String quotaCode) {
		
		String dateType = dto.getDateType();
		String date = dto.getDate();
		IndexCalDTO IndexCalDTO = new IndexCalDTO();
		IndexCalDTO.setMonitorType("drgs");
		// 注释报错
//		IndexCalDTO.setMrStdtype("year");
		IndexCalDTO.setQuotaCode(quotaCode);
		IndexCalDTO.setpType("0");
		IndexCalDTO.setDeps(dto.getDepCode());
		IndexCalDTO.setDateFrom(dto.getDateFrom());
		IndexCalDTO.setDateTo(dto.getDateTo());
		if ("1".equals(dateType)) {
			IndexCalDTO.setMrType("M");
			IndexCalDTO.setDateFrom(date);
			IndexCalDTO.setDateTo(date);
		} else if ("2".equals(dateType)) {
			//date = MonitorResultUtil.addMonth(date, GlobalData.CONFIG_MONITOR_YEAR);
			String year = date.substring(0, 4);
			//int month = Integer.valueOf(date.substring(5, 7)+"");
			IndexCalDTO.setMrType("M");
			IndexCalDTO.setDateFrom(year+"-01");
			IndexCalDTO.setDateTo(date);
			// 注释报错
//			IndexCalDTO.setMrLot(year+"Y"+month+"MC");
		}
//		List<Map<String, Object>> dataList = monitorFacade.monitor(IndexCalDTO);
		List<Map<String, Object>> dataList = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(IndexCalDTO);
		List<MonitorDep> list = new ArrayList<MonitorDep>();
		for (Map<String, Object> map : dataList) {
			MonitorDep monitorDep = new MonitorDep();
			List<DepDetail> depDetails = new ArrayList<DepDetail>();
			monitorDep.setDepCode(map.get("ccode")+"");
			monitorDep.setDepName(map.get("ddesc")+"");
			for (String key : map.keySet()) {
				DepDetail depDetail = new DepDetail();
				depDetail.setQuotaCode(key);
				depDetail.setQuotaValue(map.get(key)+"");
				depDetails.add(depDetail);
			}
			monitorDep.setDepDetails(depDetails);
			list.add(monitorDep);
		}
		dto.setMonitorDeps(list);		
	}

	@Override
	public String dataExtraction(String xmlString) {
		String resultStr=storeXMLData(xmlString);
		return resultStr;
	}
	
	/**
	 * 
	 * @methodname    :storeXMLData
	 * @description   :把xml数据存储到数据库中
	 * @param         :
	 * @author        :dongyaping
	 * @return        :
	 * @date          :2015年4月3日
	 */
	private String storeXMLData(String xmlString){
		StringBuilder sqlStr=new StringBuilder();
		Document doc=null;
		try 
		{
			//将字符串转为XML
			doc = DocumentHelper.parseText(xmlString);
		} 
		catch (DocumentException e) 
		{
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
					+ "<return>fail</return>"
					+"<reason>"+e.getMessage()+"</reason>";
		}
		
		Element root = doc.getRootElement(); //获取根节点
		String sql = "";
		if(root!=null)
		{
			sqlStr.append("begin ");
			try 
			{
				buildMedicRecordStr(root,sqlStr);//拼接插入就诊记录的字符串信息
				sqlStr.append(" end;");
				sql = sqlStr.toString().replaceAll("'null'", "''");
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
						+ "<return>fail</return>"
						+"<reason>"+e.getMessage()+"</reason>";
			}	
			try 
			{
				//jdbcTemplateObjWrapper.getjdbcTemplateObj().execute(sqlStr.toString());
				//getRepository().createSqlQuery(sqlStr.toString()).executeUpdate();
				medicalRecordApplication.executeSqlStr(sql);
			} 
			catch (Exception e) 
			{
				return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
						+ "<return>fail</return>"
						+"<reason>"+e.getMessage()+"</reason>";
			}
			
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
					+ "<return>success</return>"
					+ "<reason></reason>";
		}
		else
		{
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<return>fail</return>"
				+ "<reason>Can not get the XML element</reason>";
		}
		
	}
	
	private void buildMedicRecordStr(Element root,StringBuilder sqlStr) throws Exception
	{
		String tmpString="";
		String tmpStringx="";
		String tmpStringz="";
		String tmpStringc="";
		String tmpStringl="";
		String tmpStringr="";
		String tmpStringy="";
		Float tmpFloat;
		String tmpString1="";
		String tmpString2="";
		String tmpString3="";
		String tmpString4="";
		String ageYear = "";
		String ageMonth = "";
		String ageDay = "";
		String newBornDays = "";
		Float tmpFloat1;
		
		if(sqlStr!=null)
		{
			String temadmNo=root.elementText("AdmNo");
			if((temadmNo==null)||(temadmNo=="")){
				return ;
			}
			sqlStr.append("INSERT INTO DRGs.T_MEDICALRECORD (ID,RECORD_ID,MR_NO,PATIENT_NAME,");
			sqlStr.append("SEX,AGE_YEAR,AGE_MONTH,AGE_DAYS,MARRIAGE,DAY_OF_BIRTH,IN_DATE,IN_DEP,IN_DEP_CODE,");
			sqlStr.append("IN_WARD_CODE,IN_WARD,OUT_WAY,IN_WAY,IP_COUNT,OP_DIAGNOSIS_CODE,OP_DIAGNOSIS,OUT_DATE,OUT_DEP_CODE,OUT_DEP,");
			sqlStr.append("DEP_MASTER_CODE,DEP_MASTER,PROTOMEDICUS_CODE,PROTOMEDICUS,PHYSICIAN_CODE,PHYSICIAN,RESIDENT_DOCTOR_CODE,RESIDENT_DOCTOR,");
			sqlStr.append("PHYSICIAN_LEARN_CODE,PHYSICIAN_LEARN,INTERN_CODE,INTERN,NURSE_CODE,NURSE,");
			sqlStr.append("PAYMENT,COSTAMOUNT,COSTSELF,DANGERLEVEL,DRUGCOST,PARGROUP_NAME,DIAGNOSE_CODE_MAIN,DIAGNOSE_DESS_MAIN,NEWBORN_WEIGHT,NEWBORN_DAYS,");
			sqlStr.append("VENTILATOR_HOUR,IN_DAYS,MATERIALCOST,");
			sqlStr.append("OUT_WARD_CODE,OUT_WARD,WTMARK");
			sqlStr.append(") VALUES (");
			try 
			{
			//	sqlStr.append("'"+root.elementText("HDSD00.11.006")+"_"+root.elementText("HDSD00.11.139")+"',");//id：病案号_住院次数
				sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
				sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
				sqlStr.append("'"+root.elementText("HDSD00.11.006")+"',");//病案号
				sqlStr.append("'"+root.elementText("HDSD00.11.110")+"',");//姓名
				tmpString = root.elementText("HDSD00.11.109");//获取 性别1：男  2：女
				if("男".equals(tmpString))
				{sqlStr.append("'1',");}
				else if("女".equals(tmpString))
				{sqlStr.append("'2',");}
				else if ("未知说明".equals(tmpString))
				{sqlStr.append("'3',");}
				else
				{sqlStr.append("'"+root.elementText("HDSD00.11.109")+"',");}
				
				//年龄
				ageYear = root.elementText("HDSD00.11.079");//年龄年
				ageMonth = root.elementText("HDSD00.11.080");//年龄月
				ageDay = root.elementText("Day");//年龄日
				if (ageYear != null && ageYear.indexOf("Y")==0) {
					ageYear = ageYear.substring(1);
				} else if (ageYear != null && ageYear.indexOf("M")==0) {
					ageMonth = ageYear.substring(1);
					ageYear = "";
				} else if (ageYear != null && ageYear.indexOf("D")==0) {
					ageDay = ageYear.substring(1);
					newBornDays = ageDay;
					ageYear = "";
				}
				sqlStr.append("'" + ageYear + "',");
		        sqlStr.append("'" + ageMonth + "',");
		        sqlStr.append("'" + ageDay + "',");
		        
				//婚姻状况
		        String tem1 = root.elementText("HDSD00.11.587");
		        if ("已婚".equals(tem1))
		          sqlStr.append("'1',");
		        else if ("未婚".equals(tem1))
		          sqlStr.append("'0',");
		        else if ("离婚".equals(tem1))
		          sqlStr.append("'3',");
		        else if ("丧偶".equals(tem1))
		          sqlStr.append("'4',");
		        else if ("其他".equals(tem1))
		          sqlStr.append("'5',");
		        else {
		          sqlStr.append("'" + root.elementText("HDSD00.11.587") + "',");
		        }
		        //出生日期
		        String birthdate = "";
		        if(StringUtils.hasLength(root.elementText("HDSD00.11.014"))){
		        	birthdate = root.elementText("HDSD00.11.014");
		        	birthdate = birthdate.substring(0, 10);
		        }
		        sqlStr.append("to_date('"+birthdate+"', 'yyyy-MM-dd'),");
		        //入院日期
		        String indate = "";
		        if (StringUtils.hasLength(root.elementText("HDSD00.11.085"))) {
		        	indate = root.elementText("HDSD00.11.085");
		        	indate = indate.substring(0, 10);
		        }
		        sqlStr.append("to_date('"+indate+"', 'yyyy-MM-dd'),");
		        //入院科室
		        sqlStr.append("'" + root.elementText("HDSD00.11.084") + "',");
		        sqlStr.append("'" + root.elementText("HDSD00.11.1004") + "',");
		        //入院病区
		        sqlStr.append("'" + root.elementText("AdmSWardCode") + "',");
		        sqlStr.append("'" + root.elementText("HDSD00.11.083") + "',");
		        //离院方式
		        tmpStringl = root.elementText("HDSD00.11.057");
		        if(StringUtils.hasLength(tmpStringl)){
		        	switch (tmpStringl) {
					case "医嘱离院":
						sqlStr.append("'1',");
						break;
					case "医嘱转院":
						sqlStr.append("'2',");
						break;
					case "医嘱转社区卫生服务机构/乡镇卫生院":
						sqlStr.append("'3',");
						break;
					case "非医嘱离院":
						sqlStr.append("'4',");
						break;
					case "死亡":
						sqlStr.append("'5',");
						break;
					case "其他":
						sqlStr.append("'9',");
						break;
					default:
						sqlStr.append("'"+root.elementText("HDSD00.11.057")+"',");//离院方式
							break;
					}
		        }else{
		        	sqlStr.append("'',");//离院方式
		        }
		        
		        //入院途径
		        tmpStringr = root.elementText("HDSD00.11.086");//获取 入院途径
		        if(StringUtils.hasLength(tmpStringr)){
		        	switch (tmpStringr) {
					case "急诊":
						sqlStr.append("'1',");
						break;
					case "门诊":
						sqlStr.append("'2',");
						break;
					case "其他医疗机构转入":
						sqlStr.append("'3',");
						break;
					case "其他":
						sqlStr.append("'9',");
						break;
					default:
						sqlStr.append("'"+root.elementText("HDSD00.11.086")+"',");
						break;
					}
		        }else{
		        	sqlStr.append("'',");
		        }
				
				//住院次数
				sqlStr.append("'"+root.elementText("HDSD00.11.139")+"',");
				//门急诊诊断
				if (StringUtils.hasLength(root.elementText("HDSD00.11.074.BJ"))) {
					sqlStr.append("'" + root.elementText("HDSD00.11.074.BJ") + "',");
			        sqlStr.append("'" + root.elementText("HDSD00.11.076.BJ") + "',");
				}
				else if (StringUtils.hasLength(root.elementText("HDSD00.11.074"))) {
					sqlStr.append("'" + root.elementText("HDSD00.11.074") + "',");
			        sqlStr.append("'" + root.elementText("HDSD00.11.076") + "',");
				}
				
				//出院日期
				String outdate="";
				if(StringUtils.hasLength(root.elementText("HDSD00.11.019")))
				{
					outdate = root.elementText("HDSD00.11.019");
					outdate = outdate.substring(0, 10);
				}
				sqlStr.append("to_date('"+outdate+"', 'yyyy-MM-dd'),");
				//出院科室
				sqlStr.append("'"+root.elementText("HDSD00.11.1005")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.018")+"',");
				//科室主任
				sqlStr.append("'"+root.elementText("HDSD00.11.575")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.056")+"',");
				//主任医师（副主任）
				sqlStr.append("'"+root.elementText("HDSD00.11.576")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.137")+"',");
				//主治医师
				sqlStr.append("'"+root.elementText("HDSD00.11.577")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.138")+"',");
				//住院医师
				sqlStr.append("'"+root.elementText("HDSD00.11.578")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.141")+"',");
				//进修医师
				sqlStr.append("'"+root.elementText("HDSD00.11.580")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.054")+"',");
				//实习医师
				sqlStr.append("'"+root.elementText("HDSD00.11.581")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.088")+"',");
				//责任护士
				sqlStr.append("'"+root.elementText("HDSD00.11.579")+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.120")+"',");
				tmpStringy = root.elementText("HDSD00.11.117");//获取 医疗付费方式
				if(StringUtils.hasLength(tmpStringy)){
					switch (tmpStringy) {
					case "城镇职工基本医疗保险":
						sqlStr.append("'1',");
						break;
					case "城镇居民基本医疗保险":
						sqlStr.append("'2',");
						break;
					case "新型农村合作医疗":
						sqlStr.append("'3',");
						break;
					case "贫困救助":
						sqlStr.append("'4',");
						break;
					case "商业医疗保险":
						sqlStr.append("'5',");
						break;
					case "全公费":
						sqlStr.append("'6',");
						break;
					case "全自费":
						sqlStr.append("'7',");
						break;
					case "其他社会保险":
						sqlStr.append("'8',");
						break;
					case "其他":
						sqlStr.append("'9',");
						break;
					default:
						sqlStr.append("'"+root.elementText("HDSD00.11.117")+"',");//医疗付费方式
							break;
					}
				}else{
					sqlStr.append("'',");//医疗付费方式
				}
				
				//总费用
				String fee1=root.elementText("ZFY");
				if(fee1==null)
				{
					fee1="";
				}	
				sqlStr.append("'"+fee1+"',");
				//自付费用
				String fee2=root.elementText("ZFFY");
				if(fee2==null)
				{
					fee2="";
				}	
				sqlStr.append("'"+fee2+"',");
				sqlStr.append("'"+root.elementText("HDSD00.11.567")+"',");//危重等级
				tmpStringx= root.elementText("XIYF");//获取 西药费
				tmpStringz= root.elementText("ZHONGCHYF");//获取 中成药费
				tmpStringc= root.elementText("ZHONGCYF");//获取 中草药费
				if(tmpStringx==null){
					tmpStringx="0";
				}
				if(tmpStringz==null){
					tmpStringz="0";
				}
				if(tmpStringc==null){
					tmpStringc="0";
				}
				tmpFloat=Float.parseFloat(tmpStringx)+Float.parseFloat(tmpStringz)+Float.parseFloat(tmpStringc);
				sqlStr.append("'"+tmpFloat+"',");//药品费用
				sqlStr.append("'"+root.elementText("HDSD00.11.137")+"',");//主诊组(协和取副主任)
				
				if (StringUtils.hasLength(root.elementText("HDSD00.11.023.BJ"))) {
					sqlStr.append("'"+root.elementText("HDSD00.11.023.BJ")+"',");//主要诊断编码
					sqlStr.append("'"+root.elementText("HDSD00.11.024.BJ")+"',");//主要诊断描述
				}
				else if (StringUtils.hasLength(root.elementText("HDSD00.11.023"))) {
					sqlStr.append("'"+root.elementText("HDSD00.11.023")+"',");//主要诊断编码
					sqlStr.append("'"+root.elementText("HDSD00.11.024")+"',");//主要诊断描述
				}
				
				sqlStr.append("'"+root.elementText("HDSD00.11.107")+"',");//新生儿体重
				sqlStr.append("'"+newBornDays+"',");//新生儿天数
				sqlStr.append("'"+root.elementText("HDSD00.11.555")+"',");//呼吸机使用时间
				sqlStr.append("'"+root.elementText("HDSD00.11.087")+"',");//住院天数
				tmpString1= root.elementText("JIANCHCLF");//获取 耗材类-检查用一次性医用材料费
				tmpString2= root.elementText("ZHILCLF");//获取 耗材类-治疗用一次性医用材料费
				tmpString3= root.elementText("JIERCLF");//获取 耗材类-介入用一次性医用材料费
				tmpString4= root.elementText("SHOUSHCLF");//获取 耗材类-手术用一次性医用材料费
				if(tmpString1==null || "".endsWith(tmpString1)){
					tmpString1="0";
				}
				if(tmpString2==null || "".endsWith(tmpString2)){
					tmpString2="0";
				}
				if(tmpString3==null || "".endsWith(tmpString3)){
					tmpString3="0";
				}
				if(tmpString4==null || "".endsWith(tmpString4)){
					tmpString4="0";
				}
			tmpFloat1=Float.parseFloat(tmpString1)+Float.parseFloat(tmpString2)+Float.parseFloat(tmpString3)+Float.parseFloat(tmpString4);
			sqlStr.append("'"+tmpFloat1+"',");//材料费
			//病区
			sqlStr.append("'"+root.elementText("AdmDWardCode")+"',");
			sqlStr.append("'"+root.elementText("HDSD00.11.017")+"',");
			//卫统标识
			sqlStr.append("'"+root.elementText("WtMark")+"'");
			sqlStr.append(");");
		} catch (Exception e) 
		{
			throw e;
		}
		//插入手术信息
		if(StringUtils.hasLength(root.elementText("HDSD00.11.089.BJ")))
		{
			sqlStr.append("INSERT INTO DRGs.T_OPERATION (PARID,OPER_CODE,OPERATION,OPER_DATE,OPER_LEVEL,");
	        sqlStr.append("OPER_DOCTOR,OPER_DOCTOR_CODE,ASSIS_ONE,ASSIS_ONE_CODE,ASSIS_TWO,ASSIS_TWO_CODE,CUT_LEVEL,ANAES_WAY,ANAES_DOCTOR,OPER_TYPE) VALUES(");
	        try{
	        	//sqlStr.append("'" + root.elementText("HDSD00.11.006") + "_"+root.elementText("HDSD00.11.139") + "',");
	        	sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
	            sqlStr.append("'" + root.elementText("HDSD00.11.089.BJ") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.090.BJ") + "',");
	            String opdate = "";
	            if (root.elementText("HDSD00.11.091") != null)
	            {
	            	opdate = root.elementText("HDSD00.11.091");
	            	opdate = opdate.substring(0, 10);
	            }
	            sqlStr.append("to_date('"+opdate+"', 'yyyy-MM-dd'),");
	            sqlStr.append("'" + root.elementText("HDSD00.11.092") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.094") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.407") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.001") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.408") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.002") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.409") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.616") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.070") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.073") + "',");
	            sqlStr.append("'M'");
	            sqlStr.append(");");
	            for (int i = 0; i < 4; i++) {
	            	if ((root.elementText("HDSD00.11." + (410 + i * 15) + ".BJ") == null) || (root.elementText("HDSD00.11." + (410 + i * 15) + ".BJ") == "") && (root.elementText("HDSD00.11." + (410 + i * 15) + ".BJ") == null) || (root.elementText("HDSD00.11." + (410 + i * 15) + ".BJ") == ""))
	                    continue;
	            	sqlStr.append("INSERT INTO DRGs.T_OPERATION (PARID,OPER_CODE,OPERATION,OPER_DATE,OPER_LEVEL,");
	                sqlStr.append("OPER_DOCTOR,OPER_DOCTOR_CODE,ASSIS_ONE,ASSIS_ONE_CODE,ASSIS_TWO,ASSIS_TWO_CODE,CUT_LEVEL,ANAES_WAY,ANAES_DOCTOR,OPER_TYPE) VALUES(");
	            //    sqlStr.append("'" + root.elementText("HDSD00.11.006")+"_"+root.elementText("HDSD00.11.139") + "',");
	                sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
	                if(i==0){
	                	sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(410 + i * 15).toString() + ".BJ") +"',");
	                }else{
	                	sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(410 + i * 15).toString() + ".BJ") + "',");
	                }
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(414 + i * 15).toString() + ".BJ") + "',");
	                String opdateo = "";
	                if (StringUtils.hasLength(root.elementText("HDSD00.11." + (411 + i * 15))))
	                {
	                	opdateo = root.elementText("HDSD00.11." + (411 + i * 15));
	                	opdateo = opdateo.substring(0, 10);
	                }
	                sqlStr.append("to_date('"+opdateo+"', 'yyyy-MM-dd'),");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(413 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(416 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(415 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(418 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(417 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(420 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(419 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(618 + i * 2).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(423 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(424 + i * 15).toString()) + "',");
	                sqlStr.append("'O'");
	                sqlStr.append(");");
	            }
	        }catch ( Exception e) {
	        	e.printStackTrace();
	        }
	    }
		else if(StringUtils.hasLength(root.elementText("HDSD00.11.089")))
		{
			sqlStr.append("INSERT INTO DRGs.T_OPERATION (PARID,OPER_CODE,OPERATION,OPER_DATE,OPER_LEVEL,");
	        sqlStr.append("OPER_DOCTOR,OPER_DOCTOR_CODE,ASSIS_ONE,ASSIS_ONE_CODE,ASSIS_TWO,ASSIS_TWO_CODE,CUT_LEVEL,ANAES_WAY,ANAES_DOCTOR,OPER_TYPE) VALUES(");
	        try{
	        	//sqlStr.append("'" + root.elementText("HDSD00.11.006") + "_"+root.elementText("HDSD00.11.139") + "',");
	        	sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
	            sqlStr.append("'" + root.elementText("HDSD00.11.089") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.090") + "',");
	            String opdate = "";
	            if (root.elementText("HDSD00.11.091") != null)
	            {
	            	opdate = root.elementText("HDSD00.11.091");
	            	opdate = opdate.substring(0, 10);
	            }
	            sqlStr.append("to_date('"+opdate+"', 'yyyy-MM-dd'),");
	            sqlStr.append("'" + root.elementText("HDSD00.11.092") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.094") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.407") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.001") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.408") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.002") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.409") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.616") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.070") + "',");
	            sqlStr.append("'" + root.elementText("HDSD00.11.073") + "',");
	            sqlStr.append("'M'");
	            sqlStr.append(");");
	            for (int i = 0; i < 4; i++) {
	            	if ((root.elementText("HDSD00.11." + (410 + i * 15) + ".BJ") == null) || (root.elementText("HDSD00.11." + (410 + i * 15) + ".BJ") == "") && (root.elementText("HDSD00.11." + (410 + i * 15)) == null) || (root.elementText("HDSD00.11." + (410 + i * 15)) == ""))
	                    continue;
	            	sqlStr.append("INSERT INTO DRGs.T_OPERATION (PARID,OPER_CODE,OPERATION,OPER_DATE,OPER_LEVEL,");
	                sqlStr.append("OPER_DOCTOR,OPER_DOCTOR_CODE,ASSIS_ONE,ASSIS_ONE_CODE,ASSIS_TWO,ASSIS_TWO_CODE,CUT_LEVEL,ANAES_WAY,ANAES_DOCTOR,OPER_TYPE) VALUES(");
	            //    sqlStr.append("'" + root.elementText("HDSD00.11.006")+"_"+root.elementText("HDSD00.11.139") + "',");
	                sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
	                if(i==0){
	                	sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(410 + i * 15).toString()) +"',");
	                }else{
	                	sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(410 + i * 15).toString()) + "',");
	                }
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(414 + i * 15).toString()) + "',");
	                String opdateo = "";
	                if (StringUtils.hasLength(root.elementText("HDSD00.11." + (411 + i * 15))))
	                {
	                	opdateo = root.elementText("HDSD00.11." + (411 + i * 15));
	                	opdateo = opdateo.substring(0, 10);
	                }
	                sqlStr.append("to_date('"+opdateo+"', 'yyyy-MM-dd'),");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(413 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(416 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(415 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(418 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(417 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(420 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(419 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(618 + i * 2).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(423 + i * 15).toString()) + "',");
	                sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(424 + i * 15).toString()) + "',");
	                sqlStr.append("'O'");
	                sqlStr.append(");");
	            }
	        }catch ( Exception e) {
	        	e.printStackTrace();
	        }
	    }
		
		//循环插入诊断信息
		try 
		{
			if (StringUtils.hasLength(root.elementText("HDSD00.11.023")))
	        {
	          sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
	          sqlStr.append("DIAGNOSIS) VALUES(");
	       //   sqlStr.append("'" + root.elementText("HDSD00.11.006") +"_"+root.elementText("HDSD00.11.139") + "',");
	          sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
	          sqlStr.append("'M',");
	          sqlStr.append("'主要诊断',");
	          sqlStr.append("'" + root.elementText("HDSD00.11.023") + "',");
	          sqlStr.append("'" + root.elementText("HDSD00.11.024") + "'");
	          sqlStr.append(");");
	        } 
			else if (StringUtils.hasLength(root.elementText("HDSD00.11.023.BJ")))
	        {
	          sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
	          sqlStr.append("DIAGNOSIS) VALUES(");
	    //      sqlStr.append("'" + root.elementText("HDSD00.11.006") +"_"+root.elementText("HDSD00.11.139") + "',");
	          sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
	          sqlStr.append("'M',");
	          sqlStr.append("'主要诊断',");
	          sqlStr.append("'" + root.elementText("HDSD00.11.023.BJ") + "',");
	          sqlStr.append("'" + root.elementText("HDSD00.11.024.BJ") + "'");
	          sqlStr.append(");");
	        }
			if (StringUtils.hasLength(root.elementText("HDSD00.11.020.BJ"))){
				sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
				sqlStr.append("DIAGNOSIS) VALUES(");
			//	sqlStr.append("'" + root.elementText("HDSD00.11.006") +"_"+root.elementText("HDSD00.11.139") + "',");
				sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
				sqlStr.append("'O',");
				sqlStr.append("'其他诊断',");
				sqlStr.append("'" + root.elementText("HDSD00.11.020.BJ") + "',");
				sqlStr.append("'" + root.elementText("HDSD00.11.021.BJ") + "'");
				sqlStr.append(");");
			}
			else if (StringUtils.hasLength(root.elementText("HDSD00.11.020"))){
				sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
				sqlStr.append("DIAGNOSIS) VALUES(");
			//	sqlStr.append("'" + root.elementText("HDSD00.11.006") +"_"+root.elementText("HDSD00.11.139") + "',");
				sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
				sqlStr.append("'O',");
				sqlStr.append("'其他诊断',");
				sqlStr.append("'" + root.elementText("HDSD00.11.020") + "',");
				sqlStr.append("'" + root.elementText("HDSD00.11.021") + "'");
				sqlStr.append(");");
			}
			for (int i = 0; i < 14; i++) {
				if(StringUtils.hasLength(root.elementText("HDSD00.11." + (307 + i * 4) + ".BJ"))){
					sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
					sqlStr.append("DIAGNOSIS) VALUES(");
				//	sqlStr.append("'" + root.elementText("HDSD00.11.006") +"_"+root.elementText("HDSD00.11.139") + "',");
					sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
					sqlStr.append("'O',");
					sqlStr.append("'其他诊断',");
					sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(307 + i * 4).toString() + ".BJ") + "',");
					sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(306 + i * 4).toString() + ".BJ") + "'");
					sqlStr.append(");");
				}
				else if(StringUtils.hasLength(root.elementText("HDSD00.11." + (307 + i * 4)))){
					sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
					sqlStr.append("DIAGNOSIS) VALUES(");
				//	sqlStr.append("'" + root.elementText("HDSD00.11.006") +"_"+root.elementText("HDSD00.11.139") + "',");
					sqlStr.append("'"+root.elementText("AdmNo")+"',");//就诊记录id
					sqlStr.append("'O',");
					sqlStr.append("'其他诊断',");
					sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(307 + i * 4).toString()) + "',");
					sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(306 + i * 4).toString()) + "'");
					sqlStr.append(");");
				}
//				if ((root.elementText("HDSD00.11." + (307 + i * 4) + ".BJ") == null) || (root.elementText("HDSD00.11." + (307 + i * 4) + ".BJ") == ""))
//					continue;
//				sqlStr.append("INSERT INTO DRGs.T_DIAGNOSIS (PARID,DIAG_TYPE_CODE,DIAG_TYPE,DIAG_CODE,");
//				sqlStr.append("DIAGNOSIS) VALUES(");
//				sqlStr.append("'" + root.elementText("AdmNo") +"_"+root.elementText("HDSD00.11.139") + "',");
//				sqlStr.append("'O',");
//				sqlStr.append("'其他诊断',");
//				sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(307 + i * 4).toString() + ".BJ") + "',");
//				sqlStr.append("'" + root.elementText(new StringBuilder("HDSD00.11.").append(306 + i * 4).toString() + ".BJ") + "'");
//				sqlStr.append(");");
		    }
		} catch ( Exception e) {
			e.printStackTrace();
		}
	}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#depDRGsInfo(java.lang.String)
	 */
	@Override
	public String depDRGsInfo(String paramStr) {
		String depCode = "";
		String yearMonth = "";
		//String mrLot = "";
		String year = "";
		String drgsVerion=GlobalData.sysConfig.get("GROUP_VER");
		ObjectMapper objectMapper = new ObjectMapper();
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			depCode = strings[0].toString();
			yearMonth = strings[1].toString();
			//mrLot = yearMonth.substring(0, 4)+"Y"+Integer.valueOf(yearMonth.substring(5))+"M";
			year = yearMonth.substring(0, 4);
		}
		
		List<Object[]> annualStdList = getQueryChannelService()
				.createSqlQuery("SELECT * FROM DRGS.T_ANNUALSTD WHERE AS_YEAR = '"+ year +"'")
				.list();
		//如果当年标杆没有值，则取去年的
		if (annualStdList.size()==0) {
			year = (Integer.valueOf(year)-1)+"";
		}
		
		
		List<Object[]> depCodeList = getQueryChannelService()
				.createSqlQuery("SELECT D.DEP_CODE,D.DEP_HIS_CODE FROM DRGS.T_DEPARTMENT D")
				.list();
		Map<String, String> depHisCodeMap = new HashMap<String, String>();
		for (Object[] obj : depCodeList) {
			depHisCodeMap.put(obj[1]+"", obj[0]+"");
		}
		if (depHisCodeMap.get(depCode)!=null) {
			depCode = depHisCodeMap.get(depCode);
		}
		
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT \n ");
		sql.append("D .DRG_CODE || '|' || D .DRG_DESC, \n ");
		sql.append("COUNT (M . PMAININDEX), \n ");
		sql.append("ROUND (AVG(M .P00800000), 2), \n ");
		sql.append("AVG (R.AS_AVG_FEE), \n ");
		sql.append("ROUND ((AVG (M .P00800000) - AVG (R.AS_AVG_FEE)) * 100 / AVG (R.AS_AVG_FEE),2),  \n ");
		sql.append("ROUND (AVG (M .P00320000),2)  \n ");
		sql.append("FROM \n ");
		sql.append("DRGS.MR_IPINFO M \n ");
		sql.append("LEFT JOIN DRGS.T_PATIENTDRG P ON M.PMAININDEX = P.PARID \n ");
		sql.append("LEFT JOIN DRGS.T_DRGS D ON P .PARDRG_CODE = D .DRG_CODE \n ");
		sql.append("LEFT JOIN (SELECT * FROM DRGS.T_ANNUALSTD WHERE AS_YEAR = '"+ year +"') R ON D .DRG_CODE = R.AS_DRG_CODE \n ");
		sql.append("WHERE \n ");
		sql.append("M .P00300001 = '"+ depCode +"' \n ");
		if("MYSQL".equals(ConstantEnum.DBTYPE)){
			sql.append("AND date_format(M .P00290000, '%Y-%m') = '"+ yearMonth +"' \n ");
		}else{
			sql.append("AND TO_CHAR (M .P00290000, 'YYYY-MM') = '"+ yearMonth +"' \n ");
		}
		sql.append("AND D .VER_CODE = '"+ drgsVerion +"' \n ");
		//sql.append("AND R.AS_YEAR = '"+ year +"' \n ");
		sql.append("GROUP BY \n ");
		sql.append("D .DRG_CODE || '|' || D .DRG_DESC \n ");
		sql.append("ORDER BY \n ");
		sql.append("ROUND ((AVG (M .P00800000) - AVG (R.AS_AVG_FEE)) * 100 / AVG (R.AS_AVG_FEE),2) \n ");
		sql.append("DESC \n ");
		List<Object[]> tempList = getQueryChannelService().createSqlQuery(sql.toString()).list();

		for (Object[] data:tempList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("drgsName", data[0]);
			map.put("leaveHospitalTime", data[1]==null?"":data[1]);
			map.put("averageFee", data[2]==null?"":data[2]);
			map.put("targetCosts", data[3]==null?"":data[3]);
			map.put("superScale", data[4]==null?"":data[4]+"%");
            map.put("avgDays", data[5]==null?"":data[5]);
			dataList.add(map);
		}
		if (tempList==null || tempList.size()==0) {
			errMSG = yearMonth+"没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("total", dataList.size());
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	@Override
	public String importUserAndDep(String source, String data){
		String returnMessage = "0^成功";
		try{
			//存入人员信息
			if("U".equals(source)){
				String createOwner = "koala";
				CreateUserCommand command = new CreateUserCommand();
		        command.setCreateOwner(createOwner);
				String[] datas;
				if(StringUtils.hasLength(data) && data.split("\\^").length>0){
					datas = data.split("\\^");
					String userAccount = datas[0];
					command.setUserAccount(userAccount);
					if(datas.length>1){
						String name = datas[1];
						command.setName(name);
					}
					if(datas.length>3){
						String depCode = datas[3];
						command.setDepCode(depCode);
					}
					InvokeResult result = securityConfigFacade.createUser(command);
					if(result.isHasErrors()){
						returnMessage = "-1^"+result.getErrorMessage();
						return returnMessage;
					}
					if(datas.length>2){
						ChangeUserPasswordCommand changeUserPasswordCommmand = new ChangeUserPasswordCommand();
						changeUserPasswordCommmand.setUserAccount(userAccount);
						changeUserPasswordCommmand.setUserPassword(datas[2]);
						changeUserPasswordCommmand.setOldUserPassword("888888");
						result = securityConfigFacade.changeUserPassword(changeUserPasswordCommmand);
						if(result.isHasErrors()){
							returnMessage = "-1^"+result.getErrorMessage();
							return returnMessage;
						}
					}
					if(datas.length>6){
						String email = datas[5];
						ChangeUserEmailCommand changeUserEmailCommand = new ChangeUserEmailCommand();
						changeUserEmailCommand.setEmail(email);
						changeUserEmailCommand.setUserAccount(userAccount);
						changeUserEmailCommand.setUserPassword(datas[2]);
						result = securityConfigFacade.changeUserEmail(changeUserEmailCommand);
						if(result.isHasErrors()){
							returnMessage = "-1^"+result.getErrorMessage();
							return returnMessage;
						}
					}
					if(datas.length>22){
						String telePhone = datas[21];
						ChangeUserTelePhoneCommand changeUserTelePhoneCommand = new ChangeUserTelePhoneCommand();
						changeUserTelePhoneCommand.setTelePhone(telePhone);
						changeUserTelePhoneCommand.setUserAccount(userAccount);
						changeUserTelePhoneCommand.setUserPassword(datas[2]);
						result = securityConfigFacade.changeUserTelePhone(changeUserTelePhoneCommand);
						if(result.isHasErrors()){
							returnMessage = "-1^"+result.getErrorMessage();
							return returnMessage;
						}
					}
				}
			}else if("D".equals(source)){
				Department dep = new Department();
				String[] datas;
				if(StringUtils.hasLength(data) && data.split("\\^").length>0){
					datas = data.split("\\^");
					String depCode = datas[0];
					dep.setDepCode(depCode);
					if(datas.length>1){
						String depName = datas[1];
						dep.setDepName(depName);
					}
					if(datas.length>6){
						String depType = datas[6];
						dep.setDepType(depType);
					}
					dep.save();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			returnMessage = "-1^"+e.getMessage();
		}
		return returnMessage;
	}

	@Override
	public String comAbilityAnalysis(String year){
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			String status = "1";
			ObjectMapper objectMapper = new ObjectMapper();
			
			IndexCalDTO dto = new IndexCalDTO();
            // 注释报错代码
//			dto.setMrLot(year+"Y12MC");
			dto.setMrType("MC");
			dto.setDateFrom(year+"-01-01");
			dto.setDateTo(year+"-12-31");
			dto.setMonitorType("hosp");
			dto.setQuotaCode("ComAbilityAnalysis");
			
//			List<Map<String, Object>> resultList = monitorFacade.monitor(dto);
			List<Map<String, Object>> resultList = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(dto);
			if (resultList==null || resultList.size()==0) {
				String errMSG = year+"没有查询到数据";
				resultMap.put("data", null);
				resultMap.put("errMSG", errMSG);
			}else{
				Map<String, Object> map = resultList.get(0);
				Map<String, Object> smap = new HashMap<>();
				smap.put("CMI", map.get("CMI"));
				smap.put("DRGGroupNumber", map.get("DRGCount"));
				smap.put("timeConsumptionIndex", map.get("TimeEff"));
				smap.put("costConsumptionIndex", map.get("FeeEff"));
				smap.put("deathNumber", map.get("Risk1DeadCaseCnt"));
				resultMap.put("data", smap);
				resultMap.put("errMSG", null);
			}
			
//			InvokeResult invoke = ywcHomeFacade.getCMIDRGCount(dto);
//			List<Map<String, Object>> resultList = (List<Map<String, Object>>) invoke.getData();
//			if(resultList.size()==0){
//				String errMSG = year+"没有查询到数据";
//				resultMap.put("data", null);
//				resultMap.put("errMSG", errMSG);
//			}else{
//				List<Map<String, Object>> list = new LinkedList<>();
//				for(Map<String, Object> map: resultList){
//					Map<String, Object> smap = new HashMap<>();
//					smap.put("year", map.get("ddesc"));
//					if(map.get("CMI") != null) smap.put("CMI", map.get("CMI"));
//					if(map.get("DRGCount") != null) smap.put("DRGGroupNumber", map.get("DRGCount"));
//					if(smap.get("CMI")!=null || smap.get("DRGGroupNumber")!=null) list.add(smap);
//				}
//				resultMap.put("data", list);
//				resultMap.put("errMSG", null);
//			}
			
			resultMap.put("status", status);
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	@Override
	public String caseMixIndex(String year){
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			String status = "1";
			ObjectMapper objectMapper = new ObjectMapper();
			
			IndexCalDTO dto = new IndexCalDTO();
			// 注释报错代码
//			dto.setMrLot(year+"Y12MC");
			dto.setMrType("MC");
			dto.setDateFrom(year+"-01-01");
			dto.setDateTo(year+"-12-31");
			dto.setMonitorType("hosp");
			dto.setQuotaCode("CMIDRGCount");
			
			List<Map<String, Object>> resultList = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(dto);
			if (resultList==null || resultList.size()==0) {
				//ret = "<Status>"+date+"没有查询到数据</Status>";
				String errMSG = year+"没有查询到数据";
				resultMap.put("data", null);
				resultMap.put("errMSG", errMSG);
			}else{
				Map<String, Object> map = resultList.get(0);
				Map<String, Object> smap = new HashMap<>();
				smap.put("CMI", map.get("CMI"));
				smap.put("caseGroupNumber", map.get("DRGCount"));
				resultMap.put("data", smap);
				resultMap.put("errMSG", null);
			}
			
			resultMap.put("status", status);
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	@Override
	public String consumptionIndex(String year){
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			String status = "1";
			ObjectMapper objectMapper = new ObjectMapper();
			
			IndexCalDTO dto = new IndexCalDTO();
			// 注释报错代码
//			dto.setMrLot(year+"Y12MC");
			dto.setMrType("MC");
			dto.setDateFrom(year+"-01-01");
			dto.setDateTo(year+"-12-31");
			dto.setMonitorType("hosp");
			dto.setQuotaCode("TimeFeeEff");
			
			List<Map<String, Object>> resultList = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(dto);
			if (resultList==null || resultList.size()==0) {
				//ret = "<Status>"+date+"没有查询到数据</Status>";
				String errMSG = year+"没有查询到数据";
				resultMap.put("data", null);
				resultMap.put("errMSG", errMSG);
			}else{
				Map<String, Object> map = resultList.get(0);
				Map<String, Object> smap = new HashMap<>();
				smap.put("costConsumption", map.get("FeeEff"));
				smap.put("timeConsumption", map.get("TimeEff"));
				resultMap.put("data", smap);
				resultMap.put("errMSG", null);
			}
			
			resultMap.put("status", status);
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	@Override
	public String numberOfDeaths(String year){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		ObjectMapper objectMapper = new ObjectMapper();
		
		IndexCalDTO dto = new IndexCalDTO();
//		dto.setMrLot(year+"Y12MC");
		dto.setMrType("MC");
		dto.setDateFrom(year+"-01-01");
		dto.setDateTo(year+"-12-31");
		dto.setMonitorType("dep");
		dto.setQuotaCode("Risk1DeadCaseCnt");
		try {
			List<Map<String, Object>> list = (List<Map<String, Object>>) drgsIndexCalFacade.indexCal(dto);
			if (list==null || list.size()==0) {
				//ret = "<Status>"+date+"没有查询到数据</Status>";
				String errMSG = year+"没有查询到数据";
				resultMap.put("data", null);
				resultMap.put("errMSG", errMSG);
			}else{
				List<Map<String, Object>> resultList = new LinkedList<>();
				for(Map<String, Object> map: list){
					Map<String, Object> smap = new HashMap<>();
					smap.put("department", map.get("ddesc"));
					smap.put("number", map.get("QuotaValue"));
					resultList.add(smap);
				}
				resultMap.put("data", resultList);
				resultMap.put("errMSG", null);
			}
			
			resultMap.put("status", status);
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	@Override
	public String checkUserExists(String userAccount){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		ObjectMapper objectMapper = new ObjectMapper();
		
		try{
			User user = User.getByUserAccount(userAccount);
			if(user != null){
				resultMap.put("data", 1);
			}else{
				resultMap.put("data", 0);
			}
			resultMap.put("status", status);
			resultMap.put("errMSG", null);
			return objectMapper.writeValueAsString(resultMap);
		}catch(Exception e){
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	@Override
	public String importMedInsData(String MedInsData) {
		String path = this.getClass().getClassLoader().getResource("/").getPath();
        path = path.substring(1, path.indexOf("WEB-INF"));
        File file =new File(path+"medInsFile");
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
		File xmltxt=new File(path+"medInsFile/medIns.txt");    
		if(file.exists())    
		{//如果存在文件就删除    
			xmltxt.delete(); 
		}
		//新建文件
		try {    
	        file.createNewFile();    
	    } catch (IOException e) {    
	        e.printStackTrace();    
	    }
		//把字符串保存到文件中去
		try
		{
			FileWriter fw = new FileWriter(path+"medInsFile/medIns.txt", true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(MedInsData);
            bw.close();
            fw.close();
        } catch (Exception e) {
        	e.printStackTrace();
    	}
		List<String> list0 = new ArrayList<String>();//保存中途结算的数据
		List<String> listOutDateErr = new ArrayList<String>();//保存医保数据与首页表出院日期多条匹配的信息
		System.out.println("开始解析数据……");
        //创建一个新的字符串
        StringReader read = new StringReader(MedInsData);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder();
        try {
            //通过输入源构造一个Document
        	org.jdom.Document doc = sb.build(source);
            //取的根元素
        	org.jdom.Element root = doc.getRootElement();
            //得到根元素所有子元素的集合
            List<org.jdom.Element> medInses = root.getChildren();
            SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd");
            int mCnt = medInses.size();
            org.jdom.Element medIns = null;
            org.jdom.Element medInsInfo = null;
            String medInsInfoText = "";
            for(int i = 0;i<mCnt;i++)
            {
            	Medins m = new Medins();
            	medIns = medInses.get(i);
            	medInsInfo = medIns.getChild("mrNo");//病案号
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			m.setMrNo(medInsInfoText);
            		}
            	}
            	medInsInfo = medIns.getChild("outDate");//出院日期
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			try {
							m.setOutDate(dateSdf.parse(medInsInfoText));
						} catch (ParseException e) {
							e.printStackTrace();
						}
            		}
            	}
            	medInsInfo = medIns.getChild("inDate");//入院日期
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			try {
							m.setInDate(dateSdf.parse(medInsInfoText));
						} catch (ParseException e) {
							e.printStackTrace();
						}
            		}
            	}
            	medInsInfo = medIns.getChild("redMark");//红冲标识
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			switch (medInsInfoText) {
						case "正常":
							medInsInfoText = "1";
							break;
						case "红冲":
							medInsInfoText = "2";
							break;
						case "被红冲":
							medInsInfoText = "3";
							break;
						}
            		}
            		m.setRedMark(medInsInfoText);
            	}
            	medInsInfo = medIns.getChild("fundPay");//基金支付
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText)&&medInsInfoText.matches("^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$"))
            		{
            			m.setFundPay(Double.valueOf(medInsInfoText));
            		}
            	}
            	medInsInfo = medIns.getChild("privatePay");//自费费用
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText)&&medInsInfoText.matches("^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$"))
            		{
            			m.setPrivatePay(Double.valueOf(medInsInfoText));
            		}
            	}
            	medInsInfo = medIns.getChild("privatePay1");//自费费用一
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText)&&medInsInfoText.matches("^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$"))
            		{
            			m.setPrivatePay1(Double.valueOf(medInsInfoText));
            		}
            	}
            	medInsInfo = medIns.getChild("privatePay2");//自费费用二
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText)&&medInsInfoText.matches("^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$"))
            		{
            			m.setPrivatePay2(Double.valueOf(medInsInfoText));
            		}
            	}
            	medInsInfo = medIns.getChild("medicalCategory");//医疗类别
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			m.setMedicalCategory(medInsInfoText);
            		}
            	}
            	medInsInfo = medIns.getChild("outType");//出院类型
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			m.setOutType(medInsInfoText);
            		}
            	}
            	medInsInfo = medIns.getChild("hiType");//险种类型
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			m.setHiType(medInsInfoText);
            		}
            	}
            	medInsInfo = medIns.getChild("refuseFee");//拒付总金额
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText)&&medInsInfoText.matches("^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$"))
            		{
            			m.setRefuseFee(Double.valueOf(medInsInfoText));
            		}
            	}
            	medInsInfo = medIns.getChild("refuseReason");//拒付原因
            	if(medInsInfo!=null)
            	{
            		medInsInfoText = medInsInfo.getText().trim();
            		if(!"".equals(medInsInfoText))
            		{
            			m.setRefuseReason(medInsInfoText);
            		}
            	}
            	List<String> mrIDList  = medicalRecordApplication.findMrIdByMrNoAndOutDate(m.getMrNo(),"",dateSdf.format(m.getOutDate()));
				if("1".equals(m.getRedMark()) && (!"急诊留观".equals(m.getMedicalCategory()) || ("急诊留观".equals(m.getMedicalCategory()) && "转出院".equals(m.getOutType())))){
				//红冲为正常，不为急诊留观病例，或为急诊留观病例且出院方式为转出院，则为有效数据，其他为垃圾数据，不处理
					if(mrIDList!=null && mrIDList.size()>0){//当前医保数据在首页表中有对应信息
						if(mrIDList.size()==1)
						{//一一对应
							m.setParid(mrIDList.get(0));
						}
						else
						{//当前医保数据在首页表中有多次出院信息  记录下来
							listOutDateErr.add(m.getMrNo()+" O "+dateSdf.format(m.getOutDate()));
						}
					}else{//当前医保数据在首页表中没有对应信息
						//病案号+入院日期
						mrIDList = medicalRecordApplication.findMrIdByMrNoAndOutDate(m.getMrNo(),dateSdf.format(m.getInDate()),"");
						if(mrIDList!=null && mrIDList.size()>0)
						{//当前医保数据在首页表中有对应信息
							if(mrIDList.size()==1)
							{//一一对应
								m.setParid(mrIDList.get(0));
							}
							else
							{//当前医保数据在首页表中有多次入院信息  记录下来
								listOutDateErr.add(m.getMrNo()+" I "+m.getInDate());
							}
						}
						else
						{//未匹配成功的
							listOutDateErr.add(m.getMrNo()+" N "+m.getMrNo());
						}
					}
				}
				if(null != m.getParid() && !"".equals(m.getParid())&& !"".equals(m.getRedMark())){
					//medinses.add(medins);
					if ("中途结算".equals(m.getOutType())&&"1".equals(m.getRedMark())){//判断是否是红冲标示为正常但是中途结算病人
						list0.add(m.getMrNo()+"-"+m.getOutDate());
					}else if (!"急诊留观".equals(m.getMedicalCategory()) && "1".equals(m.getRedMark()) ) {//筛选红冲正常的非急诊留观病人
						medinsApplication.creatMedins(m);
					}else if ("急诊留观".equals(m.getMedicalCategory()) && "转出院".equals(m.getOutType()) && "1".equals(m.getRedMark()) ) {//筛选红冲正常的非急诊留观病人
						medinsApplication.creatMedins(m);
					}
				}
            }
            Date now = new Date();
    		File specialtxt=new File(path+"medInsFile/special"+dateSdf.format(now)+".txt");    
    		//新建文件
    		try {    
    			specialtxt.createNewFile();    
    	    } catch (IOException e) {    
    	        e.printStackTrace();    
    	    }
    		//把字符串保存到文件中去
    		try
    		{
    			FileWriter fw = new FileWriter(path+"medInsFile/special"+dateSdf.format(now)+".txt", true);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.append("以下是中途结算的数据 \r\n");
                for(int i= 0;i<list0.size();i++)
                {
                	bw.append(list0.get(i)+" \r\n");
                }
                bw.append("以下是入院时间、出院时间有误的数据 \r\n");
                for(int i= 0;i<listOutDateErr.size();i++)
                {
                	bw.append(listOutDateErr.get(i)+" \r\n");
                }
                bw.close();
                fw.close();
            } catch (Exception e) {
            	e.printStackTrace();
        	}
            
        } catch (org.jdom.JDOMException e) {
        	return "<Response>"
					+ "<STATUS>导入失败</STATUS>"
					+ "<MESSAGE>xml解析失败:"+e.getMessage()+"</MESSAGE>"
				 + "</Response>";
        } catch (IOException e) {
        	return "<Response>"
					+ "<STATUS>导入失败</STATUS>"
					+ "<MESSAGE>xml解析失败:"+e.getMessage()+"</MESSAGE>"
				 + "</Response>";
        }
        System.out.println("解析数据结束……");
        
        
        return "<Response>"
					+ "<STATUS>导入成功</STATUS>"
				 + "</Response>";
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#getHospitalQuotas(java.lang.String)
	 */
	@Override
	public String getHospitalQuotas(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateFrom = null;
		String dateTo = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateFrom = strings[0].toString();
			dateTo = strings[1].toString();
		}
		DepDataDto dto = new DepDataDto();
		dto.setDateFrom(dateFrom);
		dto.setDateTo(dateTo);
		
		String quotaCodes = "AvgDays,AvgFee,DrugFee,DrugRatio,TotalCaseCnt,InCaseCnt,InCaseRatio,CMI,DRGCount,TimeEff,FeeEff,Risk1DeadCaseCnt,Risk1Ratio,Risk2DeadCaseCnt,Risk2Ratio";
		
		getHospData(dto, quotaCodes);
		
		List<MonitorDep> monitorData = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorData){
			List<DepDetail> depDetails = mDep.getDepDetails();
			Map<String, Object> data = new HashMap<String, Object>();
			String totalCnt = null;
			String inCnt = null;
			data.put("date", dateFrom+"~"+dateTo);
			for (DepDetail dDetail:depDetails) {
				data.put(dDetail.getQuotaCode(), dDetail.getQuotaValue());
				if ("TotalCaseCnt".equals(dDetail.getQuotaCode())) {
					totalCnt = dDetail.getQuotaValue();
				} else if ("InCaseCnt".equals(dDetail.getQuotaCode())) {
					inCnt = dDetail.getQuotaValue();
				}
			}
			if (totalCnt != null && inCnt != null) {
				data.put("NotInCaseCnt", Integer.valueOf(totalCnt) - Integer.valueOf(inCnt));
			}
			
			dataList.add(data);
		}
		if (monitorData==null || monitorData.size()==0) {
			errMSG = dateFrom+"~"+dateTo + "没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#getDepQuotas(java.lang.String)
	 */
	@Override
	public String getDepQuotas(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateFrom = null;
		String dateTo = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateFrom = strings[0].toString();
			dateTo = strings[1].toString();
		}
		DepDataDto dto = new DepDataDto();
		dto.setDateFrom(dateFrom);
		dto.setDateTo(dateTo);
		
		String quotaCodes = "AvgDays,AvgFee,DrugFee,DrugRatio,TotalCaseCnt,InCaseCnt,InCaseRatio,CMI,DRGCount,TimeEff,FeeEff,Risk1DeadCaseCnt,Risk1Ratio,Risk2DeadCaseCnt,Risk2Ratio";
		
		getDepData(dto, quotaCodes);
		
		List<MonitorDep> monitorData = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorData){
			List<DepDetail> depDetails = mDep.getDepDetails();
			Map<String, Object> data = new HashMap<String, Object>();
			String totalCnt = null;
			String inCnt = null;
			data.put("date", dateFrom+"~"+dateTo);
			for (DepDetail dDetail:depDetails) {
				data.put(dDetail.getQuotaCode(), dDetail.getQuotaValue());
				if ("TotalCaseCnt".equals(dDetail.getQuotaCode())) {
					totalCnt = dDetail.getQuotaValue();
				} else if ("InCaseCnt".equals(dDetail.getQuotaCode())) {
					inCnt = dDetail.getQuotaValue();
				}
			}
			if (totalCnt != null && inCnt != null) {
				data.put("NotInCaseCnt", Integer.valueOf(totalCnt) - Integer.valueOf(inCnt));
			}	
			
			dataList.add(data);
		}
		if (monitorData==null || monitorData.size()==0) {
			errMSG = dateFrom+"~"+dateTo + "没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#getPatientsByQuota(java.lang.String)
	 */
	@Override
	public String getPatientsByQuota(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateFrom = null;
		String dateTo = null;
		String quota = null;
		String depCode = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateFrom = strings[0];
			dateTo = strings[1];
			if (strings.length>2) {
				quota = strings[2];
			}
			
			if (strings.length>3) {
				depCode = strings[3];
			}
			
		}
		
		IndexCalDTO dto = new IndexCalDTO();
		dto.setDateFrom(dateFrom + " 0:00:00");
		dto.setDateTo(dateTo + " 23:59:59");
		dto.setQuotaCode(quota);
		dto.setDeps(depCode);
		
		List<Map<String, Object>> medicalRecords = medicalRecordApplication.findPatientsByQuota(IndexCalAssembler.toEntity(dto));
		for (Map<String, Object> m : medicalRecords) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("date", dateFrom+"~"+dateTo);
			data.putAll(m);
			
			dataList.add(data);
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#getDrgsQuotas(java.lang.String)
	 */
	@Override
	public String getDrgsQuotas(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String status = "1";
		String errMSG = "1";
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		String dateFrom = null;
		String dateTo = null;
		String depCode = null;
		if (StringUtils.hasLength(paramStr)) {
			String[] strings = paramStr.split("\\^");
			dateFrom = strings[0];
			dateTo = strings[1];
			if (strings.length>2) {
				depCode = strings[2];
			}
		}
		DepDataDto dto = new DepDataDto();
		dto.setDateFrom(dateFrom);
		dto.setDateTo(dateTo);
		dto.setDepCode(depCode);
		
		String quotaCodes = "InCaseCnt,CMI,TimeEff,FeeEff,Risk1DeadCaseCnt,Risk1Ratio,Risk2DeadCaseCnt,Risk2Ratio,AvgDays,AvgFee,DrugFee,DrugRatio";
		
		getDrgsData(dto, quotaCodes);
		
		List<MonitorDep> monitorData = dto.getMonitorDeps();
		for (MonitorDep mDep:monitorData){
			List<DepDetail> depDetails = mDep.getDepDetails();
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("date", dateFrom+"~"+dateTo);
			for (DepDetail dDetail:depDetails) {
				data.put(dDetail.getQuotaCode(), dDetail.getQuotaValue());
			}	
			
			dataList.add(data);
		}
		if (monitorData==null || monitorData.size()==0) {
			errMSG = dateFrom+"~"+dateTo + "没有查询到数据";
		}
		
		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

/* (non-Javadoc)
 * @see com.dhcc.DRGsHosp.facade.DrgsService#deathDetail(java.lang.String)
 */
	@Override
	public String deathDetail(String yearMonth) {
		List<Map<String, Object>> result = drgsServiceApplication.findDeathDetail(yearMonth);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#lowRiskDeathNum(java.lang.String)
	 */
	@Override
	public String lowRiskDeathNum(String year) {
		List<Map<String, Object>> result = drgsServiceApplication.findLowRiskDeathNum(year);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#lowRiskDeathDetail(java.lang.String)
	 */
	@Override
	public String lowRiskDeathDetail(String yearMonth) {
		List<Map<String, Object>> result = drgsServiceApplication.findLowRiskDeathDetail(yearMonth);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#neonatalDeathNum(java.lang.String)
	 */
	@Override
	public String neonatalDeathNum(String year) {
		List<Map<String, Object>> result = drgsServiceApplication.findNeonatalDeathNum(year);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#neonatalDeathDetail(java.lang.String)
	 */
	@Override
	public String neonatalDeathDetail(String yearMonth) {
		List<Map<String, Object>> result = drgsServiceApplication.findNeonatalDeathDetail(yearMonth);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#surgicalCompNum(java.lang.String)
	 */
	@Override
	public String surgicalCompNum(String year) {
		List<Map<String, Object>> result = drgsServiceApplication.findSurgicalCompNum(year);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#surgicalCompDetail(java.lang.String)
	 */
	@Override
	public String surgicalCompDetail(String yearMonth) {
		List<Map<String, Object>> result = drgsServiceApplication.findSurgicalCompDetail(yearMonth);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DrgsService#adverseEventNum(java.lang.String)
	 */
	@Override
	public String adverseEventNum(String year) {
		List<Map<String, Object>> result = drgsServiceApplication.findAdverseEventNum(year);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	/**
	 * 
	 *  medicaQualityQuota.  
	 *  @Description：通过年月查询所有医疗质量项的数据
	 *  @Author ChenHanlin
	 *  @param yearMonth
	 *  @return 
	 *  @Date:2017年9月19日下午3:20:37
	 */
	@Override
	public String medicaQualityQuota(String yearMonth) {
//		1	死亡例数	deathNum	
//		2	低风险死亡例数	lowRiskDeathNum	
//		3	新生儿死亡例数	neonatalDeathNum	
		String asId = drgsIndexCalFacade.getStdID(yearMonth,yearMonth);
		StringBuffer sqlstrb = new StringBuffer() ;
		sqlstrb.append(" select count(1) deathNum,sum( case when std.as_risk_level = 1 then 1 else 0 end ) lowRiskDeathNum, \n ") ;
		sqlstrb.append(" sum(case when base.P00110000 is not null then 1 else 0 end) neonatalDeathNum \n ") ;
		sqlstrb.append(" from  drgs.mr_baseinfo base  \n ") ;
		sqlstrb.append(" left join drgs.mr_ipinfo ipinfo on ipinfo.pmainindex = base.pmainindex \n ") ;
		sqlstrb.append(" left join drgs.t_patientdrg pd on pd.parid = ipinfo.pmainindex \n ") ;
		sqlstrb.append(" left join drgs.t_annualstd std on pd.pardrg_code = std.as_drg_code and std.as_id = :asId \n ") ;
		sqlstrb.append(" where ipinfo.p00620001 = '5' and to_char(ipinfo.p00290000,'yyyy-mm') = :yearMonth \n ") ;
		Map<String,Object> condition = new HashMap<>();
		condition.put("asId", asId) ;
		condition.put("yearMonth", yearMonth) ;
		List<Map<String,Object>> mapListDeadNum = drgsServiceApplication.executeQueryForList(sqlstrb.toString(), condition) ;
//		4	手术并发症例数	surgicalCompNum	
		StringBuffer sql = new StringBuffer() ;
		sql.append("SELECT ");
		sql.append("COUNT(IPINFO.PMAININDEX) surgicalCompNum ");
		sql.append("FROM ");
		sql.append("DRGS.MR_BASEINFO B ");
		sql.append("LEFT JOIN drgs.mr_ipinfo ipinfo ON B .pmainindex = ipinfo.pmainindex ");
		sql.append("LEFT JOIN DRGs.t_patientdrg P ON B .pmainindex = P.parid ");
		sql.append("WHERE 1=1 ");
		sql.append("AND (");
		sql.append("P.PARDRG_CODE LIKE '___1' ");
		sql.append("OR P.PARDRG_CODE LIKE '___2' ");
		sql.append("OR P.PARDRG_CODE LIKE '___3' ");
		sql.append("OR P.PARDRG_CODE LIKE '___4' ");
		sql.append(") ");
		sql.append("AND (");
		sql.append("P.PARDRG_CODE LIKE '_A__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_B__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_C__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_D__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_E__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_F__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_G__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_H__' ");
		sql.append("OR P.PARDRG_CODE LIKE '_J__' ");
		sql.append(") ");
		sql.append("AND TO_CHAR (P00290000, 'YYYY-MM') =:yearMonth ");
		List<Map<String,Object>> mapListSurgicalCompNum = drgsServiceApplication.executeQueryForList(sql.toString(), condition) ;
		// 查询结果汇总 
		Map<String,Object> mapResult = new HashMap<>() ;
		if( mapListDeadNum !=null && mapListDeadNum.size() > 0 ) {
			mapResult.put("deathNum", mapListDeadNum.get(0).get("DEATHNUM") == null ? 0 : mapListDeadNum.get(0).get("DEATHNUM") ) ;
			mapResult.put("lowRiskDeathNum", mapListDeadNum.get(0).get("LOWRISKDEATHNUM") == null ? 0 : mapListDeadNum.get(0).get("LOWRISKDEATHNUM")) ;
			mapResult.put("neonatalDeathNum", mapListDeadNum.get(0).get("NEONATALDEATHNUM") == null ? 0 : mapListDeadNum.get(0).get("NEONATALDEATHNUM")) ;
			if( mapListSurgicalCompNum != null && mapListSurgicalCompNum.size() > 0 )  {
				mapResult.put("surgicalCompNum", mapListSurgicalCompNum.get(0).get("SURGICALCOMPNUM") == null ? 0 : mapListSurgicalCompNum.get(0).get("SURGICALCOMPNUM") ) ;
			}
		}
		List<Map<String,Object>> result = new ArrayList<>() ;
		result.add(mapResult) ;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	/**
	 * 
	 *  deathNum.  
	 *  @Description：通过年份查询死亡例数
	 *  @Author ChenHanlin
	 *  @param year
	 *  @return 
	 *  @Date:2017年9月19日下午4:40:42
	 */
	@Override
	public String deathNum(String year) {
		StringBuffer strb = new StringBuffer() ;
		strb.append(" SELECT  TO_CHAR (P00290000, 'YYYY-MM') month , COUNT(ipinfo.PMAININDEX) deathNum \n ") ;
		strb.append(" FROM DRGS.MR_IPINFO IPINFO   \n ") ;
		strb.append(" WHERE IPINFO.P00620001 = '5' AND TO_CHAR (P00290000, 'YYYY') = :year \n ") ;
		strb.append(" GROUP BY TO_CHAR (P00290000, 'YYYY-MM')  ORDER BY TO_CHAR (P00290000, 'YYYY-MM') \n ") ;
		Map<String, Object> condition  = new HashMap<>();
		condition.put("year", year) ;
		List<Map<String,Object>> mapListDeathNum = drgsServiceApplication.executeQueryForList(strb.toString(), condition  ) ;
		List<Map<String,Object>> result = new ArrayList<>() ;
		for(Map<String,Object> map : mapListDeathNum) {
			Map<String,Object> mapTemp = new HashMap<>() ;
			mapTemp.put("month", map.get("MONTH")) ;
			mapTemp.put("deathNum", map.get("DEATHNUM") == null ? 0 : map.get("DEATHNUM")) ;
			result.add(mapTemp) ;
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		resultMap.put("status", "1");
		resultMap.put("errMSG", "1");
		resultMap.put("data", result);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}
	
	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.MedicalRecordService#universalImport(java.lang.String)
	 */
	@Override
	public String universalImport(String data) {
	//	return medicalrecordNewFacade.universalMedicalrecordImport(data);
	return null;
	}
	
	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.MedicalRecordService#test(java.lang.String)
	 */
	@Override
	public String getDRGsGroupResult(String date) {
		if (date == null || date.indexOf("^")<=0) {
			return "parameter error";
		}
		String dateFrom = date.split("\\^")[0];
		String dateTo = date.split("\\^")[1];
		IndexCal dto = new IndexCal();
		dto.setDateFrom(dateFrom);
		dto.setDateTo(dateTo);
		List<Map<String, Object>> list = patientDrgApplication.findPatientDRGsData(dto);
		StringBuilder xmlResult = new StringBuilder();
		xmlResult.append("<cases>");
		for (Map<String, Object> map : list) {
			xmlResult.append("<case><case_id>");
			xmlResult.append(map.get("recordId"));
			xmlResult.append("</case_id><drg>");
			xmlResult.append(map.get("drgCode"));
			xmlResult.append("</drg><drgVer>");
			xmlResult.append(map.get("verCode"));
			xmlResult.append("</drgVer><log>");
			xmlResult.append(map.get("logInfo"));
			xmlResult.append("</log><gl01>");
			xmlResult.append(map.get("gl01"));
			xmlResult.append("</gl01><gl02>");
			xmlResult.append(map.get("gl02"));
			xmlResult.append("</gl02><gl03>");
			xmlResult.append(map.get("gl03"));
			xmlResult.append("</gl03><gl04>");
			xmlResult.append(map.get("gl04"));
			xmlResult.append("</gl04><gl05>");
			xmlResult.append(map.get("gl05"));
			xmlResult.append("</gl05><gl06>");
			xmlResult.append(map.get("gl06"));
			xmlResult.append("</gl06><gl07>");
			xmlResult.append(map.get("gl07"));
			xmlResult.append("</gl07><gl08>");
			xmlResult.append(map.get("gl08"));
			xmlResult.append("</gl08><gl081>");
			xmlResult.append(map.get("gl081"));
			xmlResult.append("</gl081><gl09>");
			xmlResult.append(map.get("gl09"));
			xmlResult.append("</gl09><gl091>");
			xmlResult.append(map.get("gl091"));
			xmlResult.append("</gl091><gl101>");
			xmlResult.append(map.get("gl101"));
			xmlResult.append("</gl101><gl102>");
			xmlResult.append(map.get("gl102"));
			xmlResult.append("</gl102><gl103>");
			xmlResult.append(map.get("gl103"));
			xmlResult.append("</gl103><gl104>");
			xmlResult.append(map.get("gl104"));
			xmlResult.append("</gl104><gl105>");
			xmlResult.append(map.get("gl105"));
			xmlResult.append("</gl105><gl106>");
			xmlResult.append(map.get("gl106"));
			xmlResult.append("</gl106><gl11>");
			xmlResult.append(map.get("gl11"));
			xmlResult.append("</gl11><glOperCode>");
			xmlResult.append(map.get("glOperCode"));
			xmlResult.append("</glOperCode><glOperName>");
			xmlResult.append(map.get("glOperName"));
			xmlResult.append("</glOperName></case>");

		}
		xmlResult.append("</cases>");
		return xmlResult.toString();
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.MedicalRecordService#getDRGsDictionary(java.lang.String)
	 */
	@Override
	public String getDRGsDictionary(String drgsVersion) {
		DRGs drgs = new DRGs();
		drgs.setVerCode(drgsVersion);
		List<DRGs> drgsList = drgsApplication.findAllDRGs(drgs);
		
		StringBuilder xmlResult = new StringBuilder();
		xmlResult.append("<drgs>");
		for (DRGs d : drgsList) {
			xmlResult.append("<drg><drg_code>");
			xmlResult.append(d.getDrgCode());
			xmlResult.append("</drg_code><drg_desc>");
			xmlResult.append(d.getDrgDesc());
			xmlResult.append("</drg_desc><drg_version>");
			xmlResult.append(d.getVerCode());
			xmlResult.append("</drg_version></drg>");
		}
		xmlResult.append("</drgs>");
		return xmlResult.toString();
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.MedicalRecordService#getDRGsBenchmark(java.lang.String)
	 */
	@Override
	public String getDRGsBenchmark(String year) {
		AnnualSTD annualSTD = new AnnualSTD();
		annualSTD.setAsYear(year);
		List<AnnualSTD> annualStdList = annualSTDApplication.findAllAnnualSTD(annualSTD);
		
		StringBuilder xmlResult = new StringBuilder();
		xmlResult.append("<benchmarks>");
		for (AnnualSTD d : annualStdList) {
			xmlResult.append("<benchmark><drg_code>");
			xmlResult.append(d.getAsDrgCode());
			xmlResult.append("</drg_code><case_cnt>");
			xmlResult.append(d.getAsTotalCase());
			xmlResult.append("</case_cnt><avg_fee>");
			xmlResult.append(d.getAsAvgFee());
			xmlResult.append("</case_cnt><avg_fee>");
			xmlResult.append(d.getAsAvgFee());
			xmlResult.append("</avg_fee><avg_days>");
			xmlResult.append(d.getAsAvgDays());
			xmlResult.append("</avg_days><dead_cnt>");
			xmlResult.append(d.getAsDeadCnt());
			xmlResult.append("</dead_cnt><weight>");
			xmlResult.append(d.getAsWeight());
			xmlResult.append("</weight><year>");
			xmlResult.append(d.getAsYear());
			xmlResult.append("</year></benchmark>");
		}
		xmlResult.append("</benchmarks>");
		return xmlResult.toString();
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.MedicalRecordService#getDRGsVersion()
	 */
	@Override
	public String getDRGsVersion() {
		List<DRGVersion> drgsVersionList = drgVersionApplication.findAllDRGVersionOrder();
		
		StringBuilder xmlResult = new StringBuilder();
		xmlResult.append("<versions>");
		for (DRGVersion d : drgsVersionList) {
			xmlResult.append("<version><ver_code>");
			xmlResult.append(d.getVerCode());
			xmlResult.append("</ver_code><ver_desc>");
			xmlResult.append(d.getVerDesc());
			xmlResult.append("</ver_desc><ver_time>");
			xmlResult.append(d.getYearTime());
			xmlResult.append("</ver_time></version>");
		}
		xmlResult.append("</versions>");
		return xmlResult.toString();
	}
	
	@Override
	public String importMedicalRecord(String data) {/*
		
		try {
			SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat timeSdf = new SimpleDateFormat("HH:mm:ss");
			System.out.println("接口导入首页数据"+dateSdf.format(new Date())+"  "+timeSdf.format(new Date()));
			
			//所有科室
			List<Department> depList = departmentApplication.findAllDepartment();
			Map<String, String> depMap = new HashMap<String, String>();//科室名称代码信息
			for (Department dep : depList) {
				depMap.put(dep.getDepName(), dep.getDepCode());
			}
			
			//解析xml文档
			Document document = DocumentHelper.parseText(data);
			//获取根节点
			Element rootNode = document.getRootElement();
			List<Element> personList = rootNode.elements();
			
			List<MedicalRecord> mrList = new ArrayList<MedicalRecord>();
		//	List<Operation> operList = new ArrayList<Operation>();
		//	List<Diagnosis> diagList = new ArrayList<Diagnosis>();
			List<Cost> costList = new ArrayList<Cost>();
			
			Map<String, Object> outDateMap = new HashMap<String, Object>();//出院月份列表
			
			for (Element person : personList) {
				String id = null;
				String mrNo = null;
				String outDate = null;//出院日期
				String ipCount = null;//住院次数
				
				List<Element> personInfo = person.elements();
				
				MedicalRecord medicalRecord = new MedicalRecord();
			//	Operation operationMain = new Operation();
			//	operationMain.setOperType("M");//主要手术
				for (Element info : personInfo) {
					String infoName = info.getName();
					
					if (("".equals(info.getText()) || info.getText()==null) && info.elements().size()==0) {
						continue;
					}
					switch (infoName) {
					 case "ADM_ID":
						medicalRecord.setRecordId(info.getText());
						break;
					 case "MR_NO":
						medicalRecord.setMrNo(info.getText());
						mrNo = info.getText();
						if (outDate != null && ipCount != null) {
							id = mrNo+"-"+outDate+"-"+ipCount;
							medicalRecord.setId(id);
						}
						break;
					 case "PATIENT_NAME":
						medicalRecord.setPatientName(info.getText());;
						break;
					 case "SEX":
						medicalRecord.setSex(info.getText());
						break;
					 case "AGE_YEAR":
						medicalRecord.setAgeYear(Double.valueOf(info.getText()));
						break;
					 case "DAY_OF_BIRTH":
						try {
							medicalRecord.setDayOfbirth(dateSdf.parse(info.getText()));
						} catch (ParseException e1) {
							e1.printStackTrace();
						}
						break;
					 case "IN_DATE":
						try {
							medicalRecord.setInDate(dateSdf.parse(info.getText()));
						} catch (ParseException e1) {
							e1.printStackTrace();
							return "<Response>"
									+ "<STATUS>导入失败</STATUS>"
									+ "<MESSAGE>入院日期出错："+e1.getMessage()+"，就诊ID："+medicalRecord.getRecordId()+"</MESSAGE>"
								 + "</Response>";
						}
						break;
					 case "OUT_DATE":
						try {
							medicalRecord.setOutDate(dateSdf.parse(info.getText()));
							outDate = dateSdf.format(medicalRecord.getOutDate());
							outDateMap.put(outDate.substring(0, 7), null);
							
							if (mrNo != null && ipCount!= null) {
								id = mrNo+"-"+outDate+"-"+ipCount;
								medicalRecord.setId(id);
							}
						} catch (ParseException e1) {
							e1.printStackTrace();
							return "<Response>"
									+ "<STATUS>导入失败</STATUS>"
									+ "<MESSAGE>出院日期出错："+e1.getMessage()+"，就诊ID："+medicalRecord.getRecordId()+"</MESSAGE>"
								 + "</Response>";
						}
						break;
						
						
					 case "IP_COUNT":
						medicalRecord.setIpCount(Double.valueOf(info.getText()));
						ipCount = info.getText();
						if (mrNo != null && outDate != null) {
							id = mrNo+"-"+outDate+"-"+ipCount;
							medicalRecord.setId(id);
						}
						break;
							
							
					 case "IN_DEP":
						medicalRecord.setInDep(info.getText());
						String inDepCode = depMap.get(info.getText());
						if (inDepCode!=null) {
							medicalRecord.setInDepcode(inDepCode);
						} else {
							String errorMsg = "本数据库不存在科室“"+info.getText()+"”，就诊ID："+medicalRecord.getRecordId();
							System.err.println(errorMsg);
							return "<Response>"
									+ "<STATUS>导入失败</STATUS>"
									+ "<MESSAGE>"+errorMsg+"</MESSAGE>"
								 + "</Response>";
						}
						break;
					 case "OUT_DEP":
						medicalRecord.setOutDep(info.getText());
						String outDepCode = depMap.get(info.getText());
						if (outDepCode!=null) {
							medicalRecord.setOutDepcode(outDepCode);
						} else {
							String errorMsg = "本数据库不存在科室“"+info.getText()+"”，就诊ID："+medicalRecord.getRecordId();
							System.err.println(errorMsg);
							return "<Response>"
									+ "<STATUS>导入失败</STATUS>"
									+ "<MESSAGE>"+errorMsg+"</MESSAGE>"
								 + "</Response>";
						}
						break;
					 case "OUT_WAY":
						medicalRecord.setOutWay(info.getText());
						break;
					 case "IN_WAY":
						medicalRecord.setInWay(info.getText());
						break;
					 case "DEP_MASTER":
						medicalRecord.setDepMaster(info.getText());
						break;
					 case "PROTOMEDICUS":
						medicalRecord.setProtomedicus(info.getText());
						break;
					 case "PHYSICIAN":
						medicalRecord.setPhysician(info.getText());
						break;
					 case "RESIDENT_DOCTOR":
						medicalRecord.setResidentDoctor(info.getText());
						break;
					 case "PARGROUP_NAME":
						medicalRecord.setPargroupName(info.getText());
						break;
					 case "PAYMENT":
						medicalRecord.setPayment(info.getText());
						break;
					 case "COSTAMOUNT":
						medicalRecord.setCostamount(Double.valueOf(info.getText()));
						break;
					 case "COSTSELF":
						medicalRecord.setCostself(Double.valueOf(info.getText()));
						break;
					 case "DRUGFEE":
						medicalRecord.setDrugcost(Double.valueOf(info.getText()));
						break;
					 case "MATERIALFEE":
						medicalRecord.setMaterialcost(Double.valueOf(info.getText()));
						break;
					 case "NEWBORN_WEIGHT":
						medicalRecord.setNewbornWeight(Double.valueOf(info.getText()));
						break;
					 case "NEWBORN_DAYS":
						medicalRecord.setNewbornDays(Double.valueOf(info.getText()));
						break;
					 case "VENTILATOR_HOUR":
						medicalRecord.setVentilatorHour(Double.valueOf(info.getText()));
						break;
					 case "IN_DAYS":
						medicalRecord.setInDays(Double.valueOf(info.getText()));
						break;
					 case "DIAGNOSE_CODE_MAIN":
						medicalRecord.setDiagnoseCodemain(info.getText());
						break;
					 case "DIAGNOSE_DESS_MAIN":
						medicalRecord.setDiagnoseDessmain(info.getText());
						break;
					case "OPER_CODE_MAIN":
						operationMain.setOperCode(info.getText());
						operationMain.setId(new Date().getTime()+"");
						break;
			        case "OPERATION_MAIN":
						operationMain.setOperation(info.getText());
						operationMain.setId(new Date().getTime()+"");
						break;
			        case "OPER_DATE_MAIN":
						try {
							operationMain.setOperDate(dateSdf.parse(info.getText()));
						} catch (ParseException e1) {
							e1.printStackTrace();
						}
						break;
			        case "OPER_TIME_MAIN":
						try {
							operationMain.setOperTime(timeSdf.parse(info.getText()));
						} catch (ParseException e1) {
							//e1.printStackTrace();
							operationMain.setOperTime(null);
						}
						break;
			        case "OPER_LEVEL_MAIN":
						operationMain.setOperLevel(info.getText());
						break;
			        case "OPER_DOCTOR_CODE_MAIN":
						operationMain.setOperDoctorcode(info.getText());
						break;
			        case "OPER_DOCTOR_MAIN":
						operationMain.setOperDoctor(info.getText());
						break;
			        case "ASSIS_ONE_CODE_MAIN":
						operationMain.setAssisOnecode(info.getText());
						break;
					case "ASSIS_ONE_MAIN":
						operationMain.setAssisOne(info.getText());
						break;
					case "ASSIS_TWO_CODE_MAIN":
						operationMain.setAssisTwocode(info.getText());
						break;
					case "ASSIS_TWO_MAIN":
						operationMain.setAssisTwo(info.getText());
						break;
					case "CUT_LEVEL_MAIN":
						operationMain.setCutLevel(info.getText());
						break;
					case "ANAES_WAY_MAIN":
						operationMain.setAnaesWay(info.getText());
						break;
					case "ANAES_DOCTOR_CODE_MAIN":
						operationMain.setAnaesDoctorcode(info.getText());
						break;
					case "ANAES_DOCTOR_MAIN":
						operationMain.setAnaesDoctor(info.getText());
						break;

					//诊断信息
					case "DIAGNOSES":
						List<Element> diags = info.elements();
						int diagOrder = 1;
						for (Element diag : diags) {
							Diagnosis diagnosis = new Diagnosis();
							diagnosis.setId(UUID.randomUUID().toString());
							diagnosis.setDiagType("其他诊断");
							diagnosis.setDiagTypecode("O");
							if (id == null) {
								id = mrNo+"-"+outDate;
							}
							diagnosis.setParid(id);
							List<Element> diagItems = diag.elements();
							for (Element diagItem : diagItems) {
								String itemName = diagItem.getName();
								switch (itemName) {
								case "DIAGNOSE_CODE_OTHER":
									diagnosis.setDiagCode(diagItem.getText());
									break;
								case "DIAGNOSE_DESS_OTHER":
									diagnosis.setDiagnosis(diagItem.getText());
									break;
								case "DIAG_ORDER":
									diagnosis.setDiagOrder(diagItem.getText());
									break;
								}
							}
							if (StringUtils.isEmpty(diagnosis.getDiagOrder())) {
								diagnosis.setDiagOrder((diagOrder++)+"");
							}
							diagList.add(diagnosis);
						}
						break;
					//手术信息
					case "OPERATIONS":
						List<Element> opers = info.elements();
						int operOrder = 1;
						for (Element oper : opers) {
							Operation operation = new Operation();
							operation.setId(UUID.randomUUID().toString());
							operation.setOperType("O");
							if (id == null) {
								id = mrNo+"-"+outDate;
							}
							
							operation.setParid(id);
							
							List<Element> operItems = oper.elements();
							for (Element operItem : operItems) {
								String itemName = operItem.getName();
								switch (itemName) {
								case "OPER_CODE":
									operation.setOperCode(operItem.getText());
									break;
						        case "OPERATION":
						        	operation.setOperation(operItem.getText());
						        	break;
						        case "OPER_DATE":
						        	try {
										operation.setOperDate(dateSdf.parse(operItem.getText()));
									} catch (ParseException e) {
										e.printStackTrace();
									}
						        	break;
						        case "OPER_TIME":
						        	try {
										operation.setOperTime(timeSdf.parse(operItem.getText()));
									} catch (ParseException e) {
										//e.printStackTrace();
										operation.setOperTime(null);
									}
						        	break;
						        case "OPER_LEVEL":
						        	operation.setOperLevel(operItem.getText());
						        	break;
						        case "OPER_DOCTOR_CODE":
						        	operation.setOperDoctorcode(operItem.getText());
						        	break;
								case "OPER_DOCTOR":
									operation.setOperDoctor(operItem.getText());
									break;
								case "ASSIS_ONE_CODE":
									operation.setAssisOnecode(operItem.getText());
									break;
								case "ASSIS_ONE":
									operation.setAssisOne(operItem.getText());
									break;
								case "ASSIS_TWO_CODE":
									operation.setAssisTwocode(operItem.getText());
									break;
								case "ASSIS_TWO":
									operation.setAssisTwo(operItem.getText());
									break;
								case "CUT_LEVEL":
									operation.setCutLevel(operItem.getText());
									break;
								case "ANAES_WAY":
									operation.setAnaesWay(operItem.getText());
									break;
								case "ANAES_DOCTOR_CODE":
									operation.setAnaesDoctorcode(operItem.getText());
									break;
								case "ANAES_DOCTOR":
									operation.setAnaesDoctor(operItem.getText());
									break;
								case "OPER_ORDER":
									operation.setOperOrder(operItem.getText());
									break;
								}
							}
							if (StringUtils.isEmpty(operation.getOperOrder())) {
								operation.setOperOrder((operOrder++)+"");
							}
							operList.add(operation);
						}
						break;
					//费用信息
					case "COSTS":
						List<Element> costs = info.elements();
						for (Element c : costs) {
							Cost cost = new Cost();
							cost.setId(UUID.randomUUID().toString());
							if (id == null) {
								id = mrNo+"-"+outDate;
							}
							
							cost.setParid(id);
							
							List<Element> costItems = c.elements();
							for (Element costItem : costItems) {
								String itemName = costItem.getName();
								switch (itemName) {
								case "COST_CUB_CODE":
									cost.setParcostSubcode(costItem.getText());
									break;
						        case "COST_FEE":
						        	cost.setCost(Double.valueOf(costItem.getText()));
						        	break;
								}
							}
							costList.add(cost);
						}
						break;
					default:
						break;
					}
				}
				if (id != null) {
					medicalRecord.setId(id);
					operationMain.setParid(id);
				}
				if (operationMain.getOperation()!=null || operationMain.getOperCode()!=null) {
					operList.add(operationMain);
				}
				mrList.add(medicalRecord);
			}
			
			//保存
			for (MedicalRecord medicalRecord : mrList) {
				diagnosisApplication.removeDiagnosisByParid(medicalRecord.getId());
				operationApplication.removeOperationByParid(medicalRecord.getId());
				costApplication.removeCostByParid(medicalRecord.getId());
				medicalRecordApplication.creatMedicalRecord(medicalRecord);
			}
			for (Operation operation : operList) {
				operationApplication.creatOperation(operation);
			}
			for (Diagnosis diagnosis : diagList) {
				diagnosisApplication.creatDiagnosis(diagnosis);
			}
			for (Cost cost : costList) {
				costApplication.creatCost(cost);
			}
			System.out.println("导入首页数据:"+mrList.size()+"条，诊断数据："+diagList.size()+"条，手术数据："+operList.size()+"条，费用数据："+costList.size()+"条。");
			
			//开始分组
			
			for (String outDate : outDateMap.keySet()) {
				GroupFuncDTO groupFuncDTO = new GroupFuncDTO();
				groupFuncDTO.setXhday("");
				groupFuncDTO.setDateFrom(outDate);
				groupFuncDTO.setDateTo(outDate);
				groupFuncDTO.setDrgVersion("北京2015版");
				groupFuncFacade.Compute(groupFuncDTO);
			}
			
			if (mrList.size()>0) {
				String groupVerCode = "";//分组器版本代码
				List<Object[]> cfgGroupVer = systemConfigApplication.cfg_codeSearch("GROUP_VER");//分组器版本
				if(!cfgGroupVer.isEmpty())
				{
					groupVerCode = cfgGroupVer.get(0)[2].toString();
				}
				else {
					groupVerCode = "";
				}
				String groupVersion=drgVersionApplication.getDrgDescByVerCode(groupVerCode);
				List<DRGs> drgList = drgsApplication.findAllDRGs(new DRGs());
				List<String> drgCodeList=new ArrayList<String>();
				for (DRGs drgs : drgList) {
					drgCodeList.add(drgs.getDrgCode());
				}
				List<PatientDrg> patientDrgList=new LinkedList<PatientDrg>();
				List<GroupingLog> groupingLogList = new ArrayList<GroupingLog>();
				List<PatientDrg> noGroupList=new LinkedList<PatientDrg>();//未分组列表
				List<PatientDrg> day60List=new LinkedList<PatientDrg>();//大于60天列表
				List<PatientDrg> noDrgList=new LinkedList<PatientDrg>();//数据库表中不存在的列表
				
				System.out.println("组装手术和诊断数据，进行分组...");
				for (int i = 0; i < mrList.size(); i++) {
					boolean is60day=false;//住院日是否大于60天
					
					HashMap<String, Object> drg=new HashMap<String, Object>();//病案信息结构体
					
					MedicalRecord medicalRecord=mrList.get(i);
					String gender="";
					if (medicalRecord.getSex()!=null && medicalRecord.getSex().equals("1")) {
						gender="男";
					}else if(medicalRecord.getSex() != null && medicalRecord.getSex().equals("2")){
						gender="女";
					}else if (medicalRecord.getSex()!=null && medicalRecord.getSex().equals("男")) {
						gender="男";
					}else if(medicalRecord.getSex() != null && medicalRecord.getSex().equals("女")){
						gender="女";
					}else {
						System.err.println("ID："+medicalRecord.getId()+",性别为："+medicalRecord.getSex());
					}
					drg.put("GENDER", gender);//性别
//					drg.put("ORG_ID", "11528");//机构ID
					
					if (medicalRecord.getMrNo()!=null) {
						drg.put("CASE_ID", medicalRecord.getMrNo());//病案号
					}
					if (medicalRecord.getAgeYear()!=null) {
						drg.put("AGE", medicalRecord.getAgeYear());//年龄
					}
					if (medicalRecord.getInDays()!=null) {
						drg.put("ACCTUAL_DAYS", medicalRecord.getInDays().intValue());//住院天数
						if (medicalRecord.getInDays()>60) {
							is60day=true;
						}
					}
					if (medicalRecord.getDiagnoseCodemain()!=null) {
						drg.put("DISEASE_CODE", medicalRecord.getDiagnoseCodemain());//主要诊断编码
					}
					if (medicalRecord.getDiagnoseDessmain()!=null) {
						drg.put("DISEASE_NAME", medicalRecord.getDiagnoseDessmain());//主要诊断名称
					}
					if (medicalRecord.getNewbornDays()!=null) {
						drg.put("SF0100", medicalRecord.getNewbornDays());//新生儿年龄（天）
					}
					if (medicalRecord.getNewbornWeight()!=null) {
						drg.put("SF0102", medicalRecord.getNewbornWeight());//新生儿入院体重（克）
					}
					if (medicalRecord.getVentilatorHour()!=null) {
						drg.put("SF0104", medicalRecord.getVentilatorHour());//呼吸机使用时间（小时）
					}
					if (medicalRecord.getOutWay()!=null) {
						drg.put("SF0108", medicalRecord.getOutWay());//离院方式
					}
					if (medicalRecord.getCostamount()!=null) {
						drg.put("TOTAL_EXPENSE", medicalRecord.getCostamount());//住院费用
					}
					
					//组装诊断数据
					boolean matched=false;
					boolean notMatch=false;
					ArrayList<HashMap<String, Object>> datalist=new ArrayList<HashMap<String,Object>>();
					for (Diagnosis diagnosis : diagList) {
						if ("M".equals(diagnosis.getDiagTypecode())) {
							continue;
						}
						HashMap<String, Object> diag=new HashMap<String, Object>();
						if (medicalRecord.getId().equals(diagnosis.getParid())) {
							if (diagnosis.getDiagCode()!=null) {
								diag.put("code", diagnosis.getDiagCode());
							}
							if (diagnosis.getDiagnosis()!=null) {
								diag.put("name", diagnosis.getDiagnosis().replaceAll("\"", "“"));//方法 replaceAll("\"", "“") 用来替换名称中可能存在的半角双引号，解决分组器报的400错误
							}
							if (!diag.isEmpty()) {
								datalist.add(diag);
							}
							notMatch = false;
							matched=true;
						}else {
							notMatch=true;
						}
						if (matched&&notMatch) {
							break;
						}
						
					}
					if (!datalist.isEmpty()) {
						drg.put("diags", datalist);
					}
					
					//组装手术数据
					matched=false;
					notMatch=false;
					datalist=new ArrayList<HashMap<String,Object>>();
					for (Operation operation : operList) {
						HashMap<String, Object> oper=new HashMap<String, Object>();
						if (medicalRecord.getId().equals(operation.getParid())) {
							if (operation.getOperCode()!=null) {
								oper.put("code", operation.getOperCode());
							}
							if (operation.getOperation()!=null) {
								oper.put("name", operation.getOperation().replaceAll("\"", "“"));//方法 replaceAll("\"", "“") 用来替换名称中可能存在的半角双引号，解决分组器报的400错误
							}
							if (!oper.isEmpty()) {
								datalist.add(oper);
							}
							notMatch = false;
							matched=true;
						}else {
							notMatch=true;
						}
						if (matched&&notMatch) {
							break;
						}
					}
					if (!datalist.isEmpty()) {
						drg.put("opers", datalist);
					}
					
					PatientDrg patientDrg=new PatientDrg();//实体类
					//住院小于60天时
					
					if (!is60day) {
						ObjectMapper objectMapper = new ObjectMapper();
						Map<String, Object> s = new HashMap<String, Object>();
						try {
							*//*********************本地分组器调用*****************************//*
							String adder = "";
							List<Object[]> cfgAdder = systemConfigApplication.cfg_codeSearch("GROUP_ADDER");
							if(!cfgAdder.isEmpty())
							{
								adder = cfgAdder.get(0)[2].toString();
							}
							URL url = new URL("http://"+adder);
							HttpURLConnection httpURLConn = (HttpURLConnection) url.openConnection();
							httpURLConn.setDoOutput(true);
							httpURLConn.setRequestMethod("POST");
							httpURLConn.connect();
							drg.put("ver", groupVersion);
							OutputStreamWriter out = new OutputStreamWriter(httpURLConn.getOutputStream(),"UTF8");
							out.write(objectMapper.writeValueAsString(drg));
							out.flush();
							out.close();
							
							// 一旦发送成功，用以下方法就可以得到服务器的回应：  
					        String sCurrentLine="";  
					        String sTotalString="";  
					        InputStream urlStream = httpURLConn.getInputStream();  
					  
					        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream,"UTF8"));  
					        while ((sCurrentLine = bufferedReader.readLine()) != null) {  
					            sTotalString += sCurrentLine + "\r\n";  
					        }
					        s = objectMapper.readValue(sTotalString, Map.class);
					        *//*********************本地分组器调用END*****************************//*
					        //patientDrg.setLogInfo(sTotalString);
						} catch (Exception e) {
							e.printStackTrace();
							System.err.println("调用接口发生错误：");
							if ("A network error occurred.".equals(e.getMessage())) {
								System.err.println("请检查网络连接");
							} else if ("The response could not be parsed.".equals(e.getMessage()) && drg.get("DISEASE_CODE")==null) {
								System.err.println("没有主诊断代码，"+"ID:"+medicalRecord.getId());
							}
							System.err.println("已中断,ID:"+medicalRecord.getId()+",drg:"+drg);
						}
						
						//*******填充数据********
						if (s.get("drg").toString().matches("^\\w{1,2}QY$")) {
							//如果drgCode为QY结尾则存为未分组
							patientDrg.setNotinCode(s.get("drg")+"");
						} else if (s.get("drg").toString().matches("^\\d{4}$")) {
							//如果drgCode为0000,9999则存为未分组
							patientDrg.setNotinCode(s.get("drg")+"");
						}else {
							patientDrg.setPardrgCode(s.get("drg")+"");//DRGs代码
							patientDrg.setMdc("MDC"+s.get("drg").toString().substring(0, 1));
						}
						patientDrg.setParid(medicalRecord.getId());
						if (groupVerCode==null) {
							patientDrg.setVerCode("");
						}else {
							patientDrg.setVerCode(groupVerCode);
						}
						
						//分组日志start
						GroupingLog groupingLog = new GroupingLog();
						groupingLog.setMrAdm(medicalRecord.getId());
						if (s.get("oper_code")!=null) {
							groupingLog.setGlOperCode(s.get("oper_code")+"");
						}
						if (s.get("oper_name")!=null) {
							groupingLog.setGlOperName(s.get("oper_name")+"");
						}
				        Class<GroupingLog> groupLogClass = GroupingLog.class;
				        Field field = null;
				        String index = "";
				        if(s.get("log")!=null){
				        	for (String string : (List<String>)s.get("log")) {
				        		index = string.replaceAll("^判断(\\d\\d)(\\.(\\d))?(\\.(\\d))?：.*$", "$1$3$5");
				        		index = index.replaceAll("^判断(\\d)(\\.(\\d))?(\\.(\\d))?：.*$", "0$1$3$5");
				        		try {
				        			field = groupLogClass.getDeclaredField("glJ" + index);
				        			field.setAccessible(true);
				        			field.set(groupingLog, string);
				        		} catch (Exception e) {
				        			e.printStackTrace();
				        		}
							}
				        	
				        	groupingLogList.add(groupingLog);
				        }
				        //分组日志end
						//*******end********
						
						if (!drgCodeList.contains(s.get("drg")) && patientDrg.getPardrgCode()!=null) {
							noDrgList.add(patientDrg);//添加到不存在列表
						}else if (patientDrg.getNotinCode()!=null) {
							noGroupList.add(patientDrg);//添加到未分组列表
						}else {
							patientDrgList.add(patientDrg);
						}
						
					} else {
						patientDrg.setParid(medicalRecord.getId());
						day60List.add(patientDrg);//添加到住院日大于60天
					}
				}
				for (PatientDrg p : noDrgList) {
					System.err.println(p.getPardrgCode());
				}
			
				System.out.println("正在保存，请稍候...");
				//暂停500毫秒
		    	try {
					Thread.sleep(500);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				
				//保存分组结果
				for (PatientDrg patientDrg : noGroupList) {
					patientDrgApplication.creatPatientDrg(patientDrg);
				}
				for (PatientDrg patientDrg : patientDrgList) {
					patientDrgApplication.creatPatientDrg(patientDrg);
				}
				for (PatientDrg patientDrg : noDrgList) {
					patientDrgApplication.creatPatientDrg(patientDrg);
				}
				//保存分组日志
				for (GroupingLog groupingLog : groupingLogList) {
					groupingLogApplication.creatGroupingLog(groupingLog);
				}
				
				//打印和显示分组的信息
		//		System.out.println("         ____   /\\   ____\n        /   |  /  \\  |   \\\n       /   /  /    \\  \\   \\\n      /   /  /  /\\  \\  \\   \\\n      |  |__|  |__|  |__|  |\n      |  ___ WANGTENG ___  |\n      \\  \\  |  |  |  |  /  /\n       \\  \\ |  |  |  | /  /\n        \\  \\|  |  |  |/  /\n         \\_____|__|_____/");
				System.out.println("==============分组情况==============");
				System.out.println(" 总病例数:"+mrList.size()+"  诊断数量:"+diagList.size()+"  手术数量:"+operList.size());
				System.out.println("已分组:"+patientDrgList.size());
				System.out.println("未分组:"+noGroupList.size());
				System.out.println("不存在:"+noDrgList.size());
				System.out.println("大于60天病例:"+day60List.size());
				System.err.println("入组率："+(patientDrgList.size()*100/(mrList.size()-day60List.size()))+"%");
				
				if (noDrgList.size()>0) {
					System.err.println("不存在的drgCode：");
//					s.append("不存在的drgCode："+"<br>");
					for (PatientDrg p : noDrgList) {
						System.err.println("ID："+p.getParid()+",drgCode："+p.getPardrgCode());
//						s.append("ID："+p.getParid()+",drgCode："+p.getPardrgCode()+"    ");
					}
				}
			}
			
			return "<Response>"
					+ "<STATUS>导入成功</STATUS>"
					+ "<MESSAGE>导入首页数据:"+mrList.size()+"条，诊断数据："+diagList.size()+"条，手术数据："+operList.size()+"条。正在进行分组...</MESSAGE>"
				 + "</Response>";
		} catch (DocumentException e) {
			e.printStackTrace();
			return "<Response>"
					+ "<STATUS>导入失败</STATUS>"
					+ "<MESSAGE>xml解析失败:"+e.getMessage()+"</MESSAGE>"
				 + "</Response>";
		}
	*/
		return null;
	}

	/**
	 * 
	 *  @Description：获取医保接口数据
	 *  @Author ZouYiyu  
	 *  @see com.dhcc.DRGsHosp.facade.DrgsService#getMedins(java.lang.String)
	 */
	@Override
	public String getMedins(String medInsData) {
		String sucFlag="医保数据抽取成功！";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//引入日期格式化方法
		// 测试xml串
		  /*String xml="<request><medins><mrNo>121444</mrNo>";
		  xml+="<outDate>2017-07-26</outDate><inDate>2017-07-25</inDate><redMark>红冲</redMark><fundPay>100</fundPay><privatePay>50</privatePay><privatePay1>20</privatePay1>";
		  xml+= "<privatePay2>25</privatePay2><medicalCategory>1</medicalCategory><outType>出院</outType><hiType>疗保险</hiType>";
		  xml+="<refuseFee>10</refuseFee><refuseReason>没有</refuseReason></medins>";
		  xml+="<medins><mrNo>123454445</mrNo>";
		  xml+= "<outDate>2017-07-26</outDate><inDate>2017-07-25</inDate><redMark>正常</redMark><fundPay>100</fundPay><privatePay>50</privatePay><privatePay1>20</privatePay1>";
		  xml+="<privatePay2>55</privatePay2><medicalCategory></medicalCategory><outType>出院</outType><hiType>基本医疗保险</hiType>";
		  xml+=	 "<refuseFee>10</refuseFee><refuseReason>有</refuseReason></medins>";
		  xml+="<medins><mrNo>12314445</mrNo>";
		  xml+= "<outDate>2017-07-26</outDate><inDate>2017-07-23</inDate><redMark>正常</redMark><fundPay>100</fundPay><privatePay>50</privatePay><privatePay1>20</privatePay1>";
		  xml+="<privatePay2>55</privatePay2><medicalCategory></medicalCategory><outType>出院</outType><hiType>基本医疗保险</hiType>";
		  xml+=	 "<refuseFee>10</refuseFee><refuseReason>有</refuseReason></medins></request>";*/
		try {
			Map<String, Object> paramMap = new HashMap<>();
			org.dom4j.Document document = DocumentHelper.parseText(medInsData);
			Element root = document.getRootElement();// 获取根节点
			String rootName = root.getName();// 根节点名称
			List<Object[]> xmlStrucList = xmlStructureApplication.getXmlStructureByParam("medIns", "", "", "");
			String caseNodeName = "";// 单病例节点的名称
			if (!xmlStrucList.isEmpty()) {
				String redMark=GlobalData.sysConfig.get("RED_MARK");
				List<String> listMark = new ArrayList<>();// 存放红冲过滤集合
				if(StringUtils.hasLength(redMark)){
					String[] redMarkFlag = redMark.split("&");
					for (String mark : redMarkFlag) {
						listMark.add(mark);// 压入前台配置的红冲过滤类型
					}	
				}
				// xml中只有一条病例
				caseNodeName = xmlStrucList.get(0)[3].toString();
				if (caseNodeName.startsWith("/" + rootName)) {
					paramMap.put("pathPrefix", "");
					paramMap.put("curNodeName", "");
					paramMap.put("num", "");
					// 将节点信息存入对应的实体字段中
					Map<String, Object> map = medInsXmlNode(root, paramMap);
					// 取出实体，该实体已经含有xml的解析信息
					Medins medins = (Medins) map.get("medins");
					//过滤掉指定红冲类型、（急诊留观+转出院）
					if (medins != null && !listMark.contains(medins.getRedMark())) {
						//压入主键
						if (medins.getOutDate() != null && medins.getInDate() != null && medins.getMrNo() != null) {
							String outDate = dateFormat.format(medins.getOutDate());
							String inDate = dateFormat.format(medins.getInDate());
							Map<String,String> mapId = drgsServiceApplication.findPmainindex(medins.getMrNo(),inDate,outDate);
							medins.setParid(mapId.get("mr_id"));
							medins.setIsAbnormal(mapId.get("flag"));
						}
						//转换医保类型，如果字典表中没有，则插入
						Map<String,String>  mapDi=drgsServiceApplication.findMedinsType(medins.getHiType());
						medins.setHiType(mapDi.get("code").toString());
						saveMedinsDate(medins);
					}
				} else {
					// xml中有多条病例
					List<Node> nodeChild = root.selectNodes("/" + rootName + "/" + caseNodeName.split("/")[1]);
					for (int i = 1; i <= nodeChild.size(); i++) {
						paramMap.put("pathPrefix", "/" + rootName);
						paramMap.put("curNodeName", nodeChild.get(i - 1).getName());
						paramMap.put("num", "[" + i + "]");
						// 将节点信息存入对应的实体字段中
						Map<String, Object> map = medInsXmlNode(root, paramMap);
						// 取出实体，该实体已经含有xml的解析信息
						Medins medins = (Medins) map.get("medins");
							//压入主键
							if (medins != null && !listMark.contains(medins.getRedMark())) {
								//压入主键
								if (medins.getOutDate() != null && medins.getInDate() != null && medins.getMrNo() != null) {
									String outDate = dateFormat.format(medins.getOutDate());
									String inDate = dateFormat.format(medins.getInDate());
									Map<String,String> mapId = drgsServiceApplication.findPmainindex(medins.getMrNo(),inDate,outDate);
									medins.setParid(mapId.get("mr_id"));
									medins.setIsAbnormal(mapId.get("flag"));
								}
								//转换医保类型，如果字典表中没有，则插入
								Map<String,String>  mapDi=drgsServiceApplication.findMedinsType(medins.getHiType());
								medins.setHiType(mapDi.get("code").toString());
								saveMedinsDate(medins);
							}	
						}
					}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
			sucFlag=e.getMessage();
		}
		return sucFlag;

	}

	/**
	 * 
	 *  medInsXmlNode.  
	 *  @Description：解析医保xml数据
	 *  @Author ZouYiyu
	 *  @param paramMap
	 *  @return 
	 *  @Date:2017年10月12日下午3:43:51
	 */
	private Map<String, Object> medInsXmlNode(Element element, Map<String, Object> paramMap) {
		Map<String, Object> map = new HashMap<>();
		String pathPrefix = paramMap.get("pathPrefix").toString();
		String curNodeName = paramMap.get("curNodeName").toString();
		String num = paramMap.get("num").toString();
		Medins medins = new Medins();
		Map<String, Object> fieldMap = medins.medInsMap();// 获取字段与属性的对应关系
		List<Object[]> medInsXmlStrucList = xmlStructureApplication.getXmlStructureByParam("medIns", "T_MEDINS", "",
				"");
		if (!medInsXmlStrucList.isEmpty()) {
			for (Object[] objects : medInsXmlStrucList) {
				// 获取xml路径
				String xpathBaseInfo = pathPrefix + objects[3].toString().replaceFirst(curNodeName, curNodeName + num);
				System.out.println("节点路径为：" + xpathBaseInfo);
				org.dom4j.Node nodeBi = element.selectSingleNode(xpathBaseInfo);
				if (nodeBi == null) {
					continue;// 当前节点不存在 跳过
				}
				try {
					// 获取节点值
					String nodeTextVal = nodeBi.getText().toString();
					// 使用反射，调用对象实体类Set方法
					DrgsIndex.setElementValue(medins, objects[4].toString(),
							objects[13] == null ? "" : objects[13].toString(), objects[12].toString(), nodeTextVal,
							objects[5] == null ? "" : objects[5].toString(), fieldMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		map.put("medins", medins);
		return map;
	}
	/**
	 * 
	 *  saveMedinsDate.  
	 *  @Description：保存医保信息
	 *  @Author ZouYiyu
	 *  @param medins 
	 *  @Date:2017年10月24日上午11:00:48
	 */
	private void saveMedinsDate(Medins medins){
		try{
			if(medins.getIsAbnormal()==null) {
				logger.error("时间："+new Date()+"--数据："+medins.getMrNo()+"-"+medins.getOutDate()+"没有主键");
				return;
			}else{
				medinsApplication.creatMedins(medins);	
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
/**
 * 
 *  @Description：转科数据解析
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.DrgsService#getTransDep(java.lang.String)
 */
	@Override
	public String getTransDep(String depDataXml) {
		String msg="数据成功抽取！";
		try {
			Map<String ,Object> paramMap=new HashMap<>();
		    org.dom4j.Document document = DocumentHelper.parseText(depDataXml);
			Element root = document.getRootElement();//获取根节点
			String rootName = root.getName();//根节点名称
			List<Object[]> xmlStrucList = xmlStructureApplication.getXmlStructureByParam("transDep","","","");
			String caseNodeName = "";//单病例节点的名称
			//xml中有一条病例
			if(!xmlStrucList.isEmpty()){
				caseNodeName = xmlStrucList.get(0)[3].toString();
				if(caseNodeName.startsWith("/"+rootName)){
					paramMap.put("pathPrefix","");
					paramMap.put("curNodeName","");
					paramMap.put("num","");
					//将节点信息存入对应的实体字段中
					Map<String,Object> map =  transDepParseXmlNode(root,paramMap);
					//取出实体，该实体已经含有xml的解析信息
					MrTransDep mrTransDep=(MrTransDep) map.get("mrTransDep");
					/************************以下为业务操作 省略********************************/
					saveMrTransDep(mrTransDep);
					
				}else{//xml中有多条病例
					List<Node> nodeChild = root.selectNodes("/"+rootName+"/"+caseNodeName.split("/")[1]);
					for(int i = 1;i<=nodeChild.size();i++){
						paramMap.put("pathPrefix","/"+rootName);
						paramMap.put("curNodeName",nodeChild.get(i-1).getName());
						paramMap.put("num","["+i+"]");
						//将节点信息存入对应的实体字段中
						Map<String,Object> map =  transDepParseXmlNode(root,paramMap);
						//取出实体，该实体已经含有xml的解析信息
						MrTransDep mrTransDep=(MrTransDep) map.get("mrTransDep");	
						/************************以下为业务操作 省略********************************/
						saveMrTransDep(mrTransDep);
					}
				}
			}
			
		} catch (DocumentException e) {
			msg=e.getMessage();
			e.printStackTrace();
		}
		return msg;
	}
	/**
	 * 
	 *  saveMrTransDep.  
	 *  @Description：处理转了科室
	 *  @Author LiuHongjun
	 *  @param mrTransDep 
	 *  @Date:2017年10月17日上午8:57:15
	 */
	public void saveMrTransDep(MrTransDep mrTransDep) {
		 try {
				if(mrTransDep.getPmainIndex()==null) {
					logger.error("时间："+new Date()+"--数据："+mrTransDep.getPt0010()+"-"+mrTransDep.getPt0011()+"没有主键","mrTransDep_xml_interface");
					return ;
				}
				//通过科室名称获取科室代码
				if(mrTransDep.getPt0010()==null && mrTransDep.getPt0011()!=null) {
					String depCode=drgsServiceApplication.getDepCodeByDesc(mrTransDep.getPt0011());
					if(StringUtils.hasLength(depCode)){
						mrTransDep.setPt0010(depCode);
					}
				}
				//通过病区名称获取科室代码
				if(mrTransDep.getPt0020()==null && mrTransDep.getPt0021()!=null) {
					String warCode=drgsServiceApplication.getWarCodeByDesc(mrTransDep.getPt0021());
					if(StringUtils.hasLength(warCode)){
						mrTransDep.setPt0020(warCode);
					}
				}
				drgsServiceApplication.saveMrTransDep(mrTransDep); 
		} catch (Exception e) {
			logger.error("时间："+new Date()+"--数据："+mrTransDep.getPt0010()+"-"+mrTransDep.getPt0011()+"错误"+e.getMessage()+"","mrTransDep_xml_interface");
			e.printStackTrace();
		}	
	}
    /**
     *  transDepParseXmlNode.
     *  @Description：解析转科科室xml
     *  @Author LiuHongjun
     *  @param paramMap
     *  @return
     *  @Date:2017年10月12日下午3:58:14
     */
    private Map<String, Object> transDepParseXmlNode(Element element, Map<String, Object> paramMap) {
         Map<String,Object> map=new HashMap<>();
         String pathPrefix = paramMap.get("pathPrefix").toString();
        String curNodeName = paramMap.get("curNodeName").toString();
        String num = paramMap.get("num").toString();
         MrTransDep mrTransDep=new MrTransDep();
         Map<String,Object> filedMap=mrTransDep.drTransDepMap();//获取字段与属性的对应关系
            List<Object[]> dailyRecordXmlStrucList = xmlStructureApplication.getXmlStructureByParam("transDep","MR_TRANSDEP", "", "");
            if (!dailyRecordXmlStrucList.isEmpty()) {
                for (Object[] objects : dailyRecordXmlStrucList) {
                    // 获取xml路径
                    String xpathBaseInfo = pathPrefix + objects[3].toString().replaceFirst(curNodeName,curNodeName+num);
                    System.out.println("节点路径为：" + xpathBaseInfo);
                    org.dom4j.Node nodeBi = element.selectSingleNode(xpathBaseInfo);
                    if(nodeBi==null){
                        continue;//当前节点不存在 跳过
                    }
                    try {
                        //获取节点值
                        String nodeTextVal = nodeBi.getText().toString();
                        String filedCode=objects[12]==null?"":objects[12].toString();
                        // 使用反射，调用对象实体类Set方法
                        DrgsIndex.setElementValue(mrTransDep, objects[4].toString(),objects[13] == null ? "" : objects[13].toString(),filedCode, nodeTextVal,objects[5] == null ? "" : objects[5].toString(),filedMap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            map.put("mrTransDep", mrTransDep);
         return map;
    }
    /**
     *
     *  @Description：外部医保接口抽取数据
     *  @Author ZouYiyu
     *  @see com.dhcc.DRGsHosp.facade.DrgsService#dragMedinsData(java.lang.String)
     */
    public String dragMedinsData(String medinsDatas){
        String tempStr = "";
        String wsUrl = "";// 医保地址
        String method = "";// 医保方法
        String ybAdd=GlobalData.sysConfig.get("YIBAO_ADDR");// 查询接口配置信息
        if (StringUtils.hasLength(ybAdd)&& ybAdd.split("θ").length>0) {
            wsUrl  = ybAdd.split("θ")[0];
            method = ybAdd.split("θ")[1];
        }
        // 动态调用
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        org.apache.cxf.endpoint.Client client = factory.createClient(wsUrl);
        String xml = "";// xml字符串
        try {
            Object[] objects = client.invoke(method, medinsDatas);
            xml = (String) objects[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        xml = xml.replaceAll("\\d\\d@%Library.GlobalCharacterStream", "");
        return getMedins(xml);
    }

	@Override
	public String getDeptDRGRatio(String paramStr) {
		if (StringUtils.hasLength(paramStr)) {
			String[] params = paramStr.split("\\^");
			if (params.length==2) {
				String year = params[0];
				String deptCode = params[1];
				List<Map<String, Object>> resultList = drgsServiceApplication.findDeptDRGRatio(year, deptCode);
				Map<String, Object> resultMap = new HashMap<>();
				ObjectMapper objectMapper = new ObjectMapper();
				resultMap.put("status", "1");
				resultMap.put("errMSG", "1");
				resultMap.put("data", resultList);
				try {
					return objectMapper.writeValueAsString(resultMap);
				} catch (JsonProcessingException e) {
					e.printStackTrace();
					return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
				}
			} else {
                return "{status:\"-1\",errMSG:\"传入参数错误\"}";
            }
		} else {
			return "{status:\"-1\",errMSG:\"传入参数错误\"}";
		}
    }

	@Override
	/**
	 * 获取某月份各科室组的DRGs指标实际值、manage_inner值、manager_yszhyyavg值
	 */
	public String depGroupDRGsQuotas(String paramStr) {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String quotas="CMI,AvgDays,TimeEff,FeeEff,TotalWeight,Risk2Ratio,Risk1Ratio,DRGCount,hiWeightCntRatio,InCaseCnt,InCaseRatio";
		String status = "1";
		String errMSG = "";

		ObjectMapper objectMapper = new ObjectMapper();

		DepDataDto dto1 = new DepDataDto();
		DepDataDto dto2 = new DepDataDto();
		DepDataDto dto3 = new DepDataDto();
		DepDataDto dto4 = new DepDataDto();
		String date = null;
		if (StringUtils.hasLength(paramStr)) {
			dto1.setDateType("1");
			dto1.setDate(paramStr);
			dto1.setMonitorType("depGroup");
			dto1.setCompareType("manage");
			dto1.setOutManageCodeYear("manager_inner");

			dto2.setDateType("1");
			dto2.setDate(paramStr);
			dto2.setMonitorType("depGroup");
			dto2.setCompareType("manage");
			dto2.setOutManageCodeYear("manager_yszhyyavg");
		} else {
			return "{status:\"-1\",errMSG:\"传入参数错误\"}";
		}

		getDepData(dto1, quotas);//第一次获取，获取指标实际值和manage_inner值
		getDepData(dto2, quotas);//第二次获取，获取manage__yszhyyavg值

		String[] quotaCodes = quotas.split(",");
		List<MonitorDep> monitorDeps1 = dto1.getMonitorDeps();//第一次获取到的指标实际值和manage_inner值
		List<MonitorDep> monitorDeps2 = dto2.getMonitorDeps();//第二次获取到的manage__yszhyyavg值

//		//将获取到的指标值放进一个listMap
		for (MonitorDep mDep:monitorDeps1){//循环第一次获取到的值，放入data
			String depCode = mDep.getDepCode();
			String depName = mDep.getDepName();
			Map<String, Object> data = new HashMap<String, Object>();
			List<DepDetail> depDetails = mDep.getDepDetails();
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				for(int i=0;i<quotaCodes.length;i++){
					if(quotaCodes[i].equals(quotaCode)){
						data.put(quotaCodes[i], quotaValue);
					}else if((quotaCodes[i]+"cc").equals(quotaCode)){
						data.put(quotaCodes[i]+"_inner", quotaValue);
					}
				}
			}
			//循环第二次获取到的值，将与科室组对应的manage__yszhyyavg值放入data
			for (MonitorDep mDep2:monitorDeps2){
				String depCode2 = mDep2.getDepCode();
				List<DepDetail> depDetails2 = mDep2.getDepDetails();
				if(depCode.equals(depCode2)){
					for (DepDetail dDetail:depDetails2) {
						String quotaCode = dDetail.getQuotaCode();
						String quotaValue = dDetail.getQuotaValue();
						for(int i=0;i<quotaCodes.length;i++){
							if((quotaCodes[i]+"cc").equals(quotaCode)){
								data.put(quotaCodes[i]+"_yszhyyavg", quotaValue);
							}
						}
					}

				}
			}
			data.put("DepGroupCode", depCode);
			data.put("DepGroupName", depName);
			dataList.add(data) ;
		}


		// 求全院的值
		if (StringUtils.hasLength(paramStr)) {
			dto3.setDateType("1");
			dto3.setDate(paramStr);
			dto3.setMonitorType("hosp");
			dto3.setCompareType("manage");
			dto3.setOutManageCodeYear("manager_inner");

			dto4.setDateType("1");
			dto4.setDate(paramStr);
			dto4.setMonitorType("hosp");
			dto4.setCompareType("manage");
			dto4.setOutManageCodeYear("manager_yszhyyavg");
		} else {
			return "{status:\"-1\",errMSG:\"传入参数错误\"}";
		}
		getDepData(dto3, quotas);//第三次获取，获取全院指标实际值和manage_inner值
		getDepData(dto4, quotas);//第四次获取，获取全院manage__yszhyyavg值
		List<MonitorDep> monitorDeps3 = dto3.getMonitorDeps();//第三次获取到的全院指标实际值和manage_inner值
		List<MonitorDep> monitorDeps4 = dto4.getMonitorDeps();//第四次获取到的全院manage__yszhyyavg值
		//将获取到的指标值放进一个listMap
		for (MonitorDep mDep:monitorDeps3){//循环第一次获取到的值，放入data
			String depCode = mDep.getDepCode();
			String depName = mDep.getDepName();
			Map<String, Object> data = new HashMap<String, Object>();
			List<DepDetail> depDetails = mDep.getDepDetails();
			for (DepDetail dDetail:depDetails) {
				String quotaCode = dDetail.getQuotaCode();
				String quotaValue = dDetail.getQuotaValue();
				for(int i=0;i<quotaCodes.length;i++){
					if(quotaCodes[i].equals(quotaCode)){
						data.put(quotaCodes[i], quotaValue);
					}else if((quotaCodes[i]+"cc").equals(quotaCode)){
						data.put(quotaCodes[i]+"_inner", quotaValue);
					}
				}
			}
			//循环第二次获取到的值，将与科室组对应的manage__yszhyyavg值放入data
			for (MonitorDep mDep2:monitorDeps4){
				String depCode2 = mDep2.getDepCode();
				List<DepDetail> depDetails2 = mDep2.getDepDetails();
				if(depCode.equals(depCode2)){
					for (DepDetail dDetail:depDetails2) {
						String quotaCode = dDetail.getQuotaCode();
						String quotaValue = dDetail.getQuotaValue();
						for(int i=0;i<quotaCodes.length;i++){
							if((quotaCodes[i]+"cc").equals(quotaCode)){
								data.put(quotaCodes[i]+"_yszhyyavg", quotaValue);
							}
						}
					}
				}
			}
			data.put("DepGroupCode", "all");
			data.put("DepGroupName", "全院");
			dataList.add(data) ;
		}
		if (monitorDeps1==null || monitorDeps1.size()==0) {
			errMSG = date+"没有查询到数据";
		}

		resultMap.put("status", status);
		resultMap.put("errMSG", errMSG);
		resultMap.put("data", dataList);
		try {
			return objectMapper.writeValueAsString(resultMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "{status:\"-1\",errMSG:\""+e.getMessage()+"\"}";
		}
	}



}
